<!DOCTYPE html>
<html>
    <head>
        <title>File Manager</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0 user-scalable=no">
        <link rel="stylesheet" href="../../script/semantic/semantic.min.css">
        <link rel="icon" type="image/png" href="./img/small_icon.png">
        <link rel="manifest" crossorigin="use-credentials" href="manifest.json">
        <script type="text/javascript" src="../../script/jquery.min.js"></script>
        <script type="text/javascript" src="../../script/semantic/semantic.min.js"></script>
        <script type="text/javascript" src="../../script/ao_module.js"></script>
        <script type="text/javascript" src="../../script/forge-sha256.min.js"></script>
        <script type="text/javascript" src="../../script/qrcode.min.js"></script>
        <script type="text/javascript" src="../../script/applocale.js"></script>
        <link rel="stylesheet" href="../../script/ao.css">
        <link rel="stylesheet" href="file_explorer.css">
        <script>
             window.mobilecheck = function() {
                var check = false;
                (function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))) check = true;})(navigator.userAgent||navigator.vendor||window.opera);
                return check;
            };
        </script>
        <style>
            
        </style>
    </head>
    <body class="whiteTheme">
        <div id="navibar" class="navibar">
            <!-- File Opr Group-->
            <button class="fileOprBtn tabletAndDesktopOnly" title="Open" onclick="openViaButton();"><img class="opricon" src="img/opr/open.svg"><p class="oprtxt" locale="fileopr/Open">Open</p></button>
            <button class="fileOprBtn tabletAndDesktopOnly" title="Copy" onclick="copy();"><img class="opricon" src="img/opr/copy.svg"><p class="oprtxt" locale="fileopr/Copy">Copy</p></button>
            <button class="fileOprBtn tabletAndDesktopOnly" title="Paste" onclick="paste();"><img class="opricon" src="img/opr/paste.svg"><p class="oprtxt" locale="fileopr/Paste">Paste</p></button>
            <div class="fileoprGroupDivider tabletAndDesktopOnly" style="display: inline-block; vertical-align: top;">
                <button class="fileoprSmallBtn" title="Open with" onclick="openWith();"><i class="external icon"></i> <span locale="fileopr/Open with" style="font-size: 0.9em !important;">Open With</span></button><br>
                <button class="fileoprSmallBtn" title="Cut" onclick="cut();"><i class="blue cut icon"></i> <span locale="fileopr/Cut">Cut</span></button><br>
                <button class="fileoprSmallBtn" title="Rename" onclick="rename();"><i class="teal i cursor icon"></i> <span locale="fileopr/Rename">Rename</span></button>
            </div>
            <button class="fileOprBtn" title="Upload" onclick="upload(); exitMultiSelectMode();"><img class="opricon" src="img/opr/upload.svg"><p class="oprtxt wideScreenOnly" locale="fileopr/Upload">Upload</p></button>
            <button class="fileOprBtn" title="Download" onclick="downloadFile(); exitMultiSelectMode();"><img class="opricon" src="img/opr/download.svg"><p class="oprtxt wideScreenOnly" locale="fileopr/Download">Download</p></button>
            <div class="fileoprGroupDivider" style="display: inline-block; vertical-align: top;"></div>
            <button class="twolines fileOprBtn" title="New Folder" onclick="newFolder(); exitMultiSelectMode();"><img class="opricon" src="img/opr/new_folder.svg"><p class="oprtxt wideScreenOnly" locale="fileopr/New Folder">New<br>Folder</p></button>
            <div class="fileoprGroupDivider tabletAndDesktopOnly" style="display: inline-block; vertical-align: top;">
                <button class="fileoprSmallBtn" title="New File" onclick="newfile();"><i class="file outline icon"></i> <span locale="fileopr/New File">New File</span></button><br>
                <button class="fileoprSmallBtn" title="Create Zip" onclick="zipFile();"><i class="brown zip file icon"></i> <span locale="fileopr/Create Zip">Create Zip</span></button><br>
                <button class="fileoprSmallBtn" title="Unzip Here" onclick="unzipHere();"><i class="inbox icon"></i> <span locale="fileopr/Unzip Here">Unzip Here</span></button><br>
            </div>
            <div class="fileoprGroupDivider tabletAndDesktopOnly" style="display: inline-block; vertical-align: top;">
                <button class="fileoprSmallBtn" title="Refresh" onclick="refreshList();"><i class="green refresh icon"></i> <span locale="fileopr/Refresh">Refresh</span></button><br>
                <button class="fileoprSmallBtn" title="Home" onclick="openHomeDir();"><i class="home icon"></i> <span locale="fileopr/Home">Home</span></button><br>
                <button class="fileoprSmallBtn" title="File Info" onclick="showFileProperties();"><i class="blue info circle icon"></i> <span locale="fileopr/File Info">File Info</span></button><br>
            </div>
            <button class="fileOprBtn tabletAndDesktopOnly" title="Delete" onclick="deleteFile();"><img class="opricon" src="img/opr/delete.svg"><p class="oprtxt" locale="fileopr/Delete">Delete</p></button>
            <button class="fileOprBtn" title="Share File" onclick="shareFile();"><img class="opricon" src="img/opr/share.svg"><p class="oprtxt wideScreenOnly" locale="fileopr/Share">Share</p></button>
            <div class="fileoprGroupDivider" style="display: inline-block; vertical-align: top;"></div>
            <button class="mobileOnly mobileFileOprMenu" onclick="toggleMobileSidebar(true);">
                <i class="ui large bars icon"></i>
            </button>
            <div style="display: inline-block; vertical-align: top;">
                <select id="sortingMethodSelector" title="Sorting Method" class="ui basic borderless mini dropdown" onchange="updateSortingMethods();" autocomplete="off" style="min-width: 10em !important;">
                    <option value="default" locale="menu/sort/asc">Ascending</option>
                    <option value="reverse" locale="menu/sort/desc">Descending</option>
                    <option value="smallToLarge" locale="menu/sort/small">Smallest</option>
                    <option value="largeToSmall" locale="menu/sort/large"> Largest</option>
                    <option value="mostRecent" locale="menu/sort/mostrecent">Most Recent</option>
                    <option value="leastRecent" locale="menu/sort/leastrecent">Least Recent</option>
                    <option value="fileTypeAsce" locale="menu/sort/typeAsc">File Type (Asce)</option>
                    <option value="fileTypeDesc" locale="menu/sort/typeDes">File Type (Desc)</option>
                    <option value="smart" locale="menu/sort/smart">Smart</option>
                </select>
               <div class="buttons viewportBtns">
                    <!-- Viewport-->
                    <button class="ui icon tiny button videmode" mode="grid" title="Block View" onclick="changeViewMode(this);"><i class="block layout icon"></i></button>
                    <button class="ui icon tiny button videmode" mode="list" title="List View" onclick="changeViewMode(this);"><i class="align justify icon"></i></button>
                    <button class="ui icon tiny button videmode" mode="details" title="Detail View" onclick="changeViewMode(this);"><i class="list ul icon"></i></button>
                    <div class="fileoprGroupDivider" style="display: inline-block; height: 30px; vertical-align: bottom; margin-left: -0.2em; padding-right: 0.4em;"></div>
                    <button id="togglePropertiesViewBtn" class="ui icon tiny button videmode propbar" title="Show Properties" onclick="togglePropertiesView(this);"><i class="columns icon"></i></button>
               </div>  
            </div>

            <!-- Mobile Navi-bar -->
            <div id="mobileNaviBar" class="ui right fixed vertical menu" style="display:none;">
                <div class="mobileFileOprMenuToggle" onclick="toggleMobileSidebar(false);">
                    <img src="img/icon.svg" class="logo"></img>
                    <i class="large times icon"></i>
                </div>
                <!-- Sorting Mode Selector-->
                <div id="mobileSortDropdown">

                </div>
                <!-- File Operation Buttons -->
                <div class="fileoprBtnMobile" title="Open" onclick="openViaButton(); toggleMobileSidebar(false, exitMultiSelectMode);"><img class="opricon" src="img/opr/open.svg"><p class="oprtxt" locale="fileopr/Open">Open</p></div>
                <div class="fileoprBtnMobile" title="Copy" onclick="copy(); toggleMobileSidebar(false, exitMultiSelectMode);"><img class="opricon" src="img/opr/copy.svg"><p class="oprtxt" locale="fileopr/Copy">Copy</p></div>
                <div class="fileoprBtnMobile" title="Paste" onclick="paste(); toggleMobileSidebar(false, exitMultiSelectMode);"><img class="opricon" src="img/opr/paste.svg"><p class="oprtxt" locale="fileopr/Paste">Paste</p></div>
                <div class="fileoprBtnMobile" title="Delete" onclick="deleteFile(); toggleMobileSidebar(false, exitMultiSelectMode);"><img class="opricon" src="img/opr/delete.svg"><p class="oprtxt" locale="fileopr/Delete">Delete</p></div>
                <button class="fileoprSmallBtnMobile" title="Multi Select" onclick="toggleCtrl(); toggleMobileSidebar(false);"> <i class="mouse pointer icon"></i> <span locale="fileopr/Multi Select">Multi-select</span></button><br>
                <button class="fileoprSmallBtnMobile" title="Select All" onclick="selectAll(); toggleMobileSidebar(false);"> <i class="blue plus square icon"></i> <span locale="fileopr/Select All">Select All</span></button><br>
                <button class="fileoprSmallBtnMobile" title="Clear Selection" onclick="clearSelection(); toggleMobileSidebar(false, exitMultiSelectMode);"> <i class="remove icon"></i> <span locale="fileopr/Clear Select">Clear Selection</span></button><br>
                <button class="fileoprSmallBtnMobile" title="New File" onclick="newfile();"><i class="file outline icon"></i> <span locale="fileopr/New File">New File</span></button><br>
                <button class="fileoprSmallBtnMobile" title="Open with" onclick="openWith(); toggleMobileSidebar(false);"><i class="external icon"></i> <span locale="fileopr/Open with">Open With</span></button><br>
                <button class="fileoprSmallBtnMobile" title="Cut" onclick="cut(); toggleMobileSidebar(false, exitMultiSelectMode);"><i class="blue cut icon"></i> <span locale="fileopr/Cut">Cut</span></button><br>
                <button class="fileoprSmallBtnMobile" title="Rename" onclick="rename(); toggleMobileSidebar(false);"><i class="teal i cursor icon"></i> <span locale="fileopr/Rename">Rename</span></button>
                <button class="fileoprSmallBtnMobile" title="Create Zip" onclick="zipFile(); toggleMobileSidebar(false, exitMultiSelectMode);"><i class="brown zip file icon"></i> <span locale="fileopr/Create Zip">Create Zip</span></button><br>
                <button class="fileoprSmallBtnMobile" title="Unzip Here" onclick="unzipHere(); toggleMobileSidebar(false, exitMultiSelectMode);"><i class="inbox icon"></i> <span locale="fileopr/Unzip Here">Unzip Here</span></button><br>
                <button class="fileoprSmallBtnMobile" title="Refresh" onclick="refreshList(); toggleMobileSidebar(false);"><i class="green refresh icon"></i> <span locale="fileopr/Refresh">Refresh</span></button><br>
                <button class="fileoprSmallBtnMobile" title="Home" onclick="openHomeDir(); toggleMobileSidebar(false, exitMultiSelectMode);"><i class="home icon"></i> <span locale="fileopr/Home">Home</span></button><br>
                <button class="fileoprSmallBtnMobile" title="File Info" onclick="showFileProperties(); toggleMobileSidebar(false, exitMultiSelectMode);"><i class="blue info circle icon"></i> <span locale="fileopr/File Info">File Info</span></button><br>
            </div>
            <br>
            <!-- Directoy navigations -->
            <div class="addressBar">
                <button id="backbtn" class="navibarBtn" onclick="previosPath();" title="Back"><i class="left arrow icon"></i></button>
                <button id="ppbtn" class="navibarBtn" onclick="parentDir();" title="Parent Folder"><i class="up arrow icon"></i></button>

                <button class="navibarBtn" onclick="toggleSidebar();"  title="Toggle Folder List"><i class="content icon"></i></button>
                <button  class="navibarBtn DarkThemeToggle inverted" title="Dark Theme" onclick="toggleDarkTheme();"><i class="moon icon" id="darkthemebtn"></i></button>

                <div id="pathDisplayField" class="ui breadcrumb addressText pathDisplay desktopOnly" onclick="showEditCurrentPathInput(event);">
                    <div class="section selectable"><i class="folder icon"></i> user</div>
                    <div class="divider">:/</div>
                    <div class="section selectable">Desktop</div>
                </div>
                <button id="editPathBtn" class="navibarBtn" style="margin-left: 0.4em;" title="Edit Path" onclick="showEditCurrentPathInput(event)"><i class="ui edit icon"></i></button>
                <div id="pathInputField" class="ui action mini input" style="display:none;">
                    <input type="text" style="min-width: 200px;" placeholder="Type a path and press enter" onkeydown="handleOpenPathKeydown(event);">
                    <button class="ui icon basic button" title="Open" onclick="openEnteredPath(this);">
                        <i class="checkmark icon"></i>
                    </button>
                </div>
                <button id="searhbtn" class="navibarBtn"  title="Search" onclick="toggleSearch();"><i class="search icon"></i></button>
            </div>
            
             <div class="mobilePathDisplayWrapper">
                <div id="mobilePathDisplay" style="width:100%;" class="ui pathDisplay breadcrumb addressText mobileOnly">
                    <div class="section selectable"><i class="folder icon"></i> user</div>
                    <div class="divider">:/</div>
                    <div class="section selectable">Desktop</div>
                </div>
             </div>
             <div class="searchbar" style="display:none;">
                <div class="searInputBar" style="width: 80%; display:inline-block; margin-top:-4px;">
                    <div class="ui mini fluid input">
                        <input autocomplete="off" id="searchInput" type="text" placeholder="File Search (Start wildcard search with / , e.g. /*.mp3)" onkeypress="handleSearchBarPress(event);">
                    </div>
                </div>
                <button class="navibarBtn" title="Case Sensitive" onclick="toggleCaseSensitive(this);" style="margin-left: 0.4em;">Aa</button>
                <button class="navibarBtn" title="Search" onclick="handleSearch();"><i class="search icon"></i></button>
                <button class="navibarBtn" title="Clear Search" onclick="hideSearchBar();"><i class="red remove icon"></i></button>
            </div>
            <div class="msgbox" style="z-index:999; display:none;">
                <i class="checkmark icon"></i> <span>No Message</span>
                <div class="closeMsgButton" onclick="$(this).parent().stop().slideUp('fast');"><i class="caret down icon"></i></div>
            </div>
        </div>
       
        <div id="mainWindow">
            <div id="directorySidebar">
                <div id="userroot" class="ui list" style="padding-top:0px !important;">
                    <p class="dir item" style="opacity: 0.8;"><span locale="message/initiating">Initiating</span></p>
                </div>
                <div class="ui divider"></div>
                <div id="storageroot" class="ui list" style="padding-top:0px !important;">
                    <p class="dir item"  style="opacity: 0.8;"><span locale="message/initiating">Initiating</span></p>
                </div>
                <!-- <div class="ui divider"></div>
                <div id="networkneibour" class="ui list" style="padding-top:0px !important;">
                    
                </div> -->
                <div class="ui divider"></div>
                <p id="selectInfo"></p>
            </div>
            <div id="folderView" ondrop="drop(event)" ondragover="allowDrop(event)">
                <div id="folderList" class="fileviewList">

                </div>
                <div id="fileList" class="fileviewList">

                </div>
                <br>
            </div>
            <div id="propertiesView" class="small" style="display:none;">
                <div class="preview" style="margin-top: 0.4em;">
                    <img class="ui fluid image" >
                </div>
                <h3 class="ui header" style="margin-top: 0.4em;">
                    <span class="filename" style="word-break: break-all;" locale="sidebar/default/nofileselected">No File Selected</span>
                    <div class="sub header vpath"  style="word-break: break-all;" locale="sidebar/default/instruction">Select a file to view file properties</div>
                </h3>
                <table class="ui very basic table">
                    <tbody class="propertiesTable">
                        
                    </tbody>
                </table>
                <div style="height: 34px;">
                    <div class="ui right floated buttons">
                        <button style="min-width: 2.5em;" title="Share File" class="ui basic icon button shareBtn" onclick="shareFile();"><i class="share alternate icon"></i></button>
                        <button style="min-width: 2.5em;" title="Expand Properties Sidebar" class="ui basic icon button sizeToggle" onclick="togglePreviewWindowSize();"><i class="expand icon"></i></button>
                    </div>
                </div>
            </div>
        </div>
        <!-- Other popup windows -->
        <div class="popupWrapper"></div>
        <!-- Overwrite Selection Box-->
        <div id="overwriteModeSelection" class="popup" style="display:none;">
            <div class="popupheader">
                <i class="paste icon"></i> <span locale="opr/overwrite/title">Replace, Keep or Skip Files</span> 
                <div class="popupcloser" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i>
                </div>
            </div>
            <div class="popupcontent" style="padding:12px;">
                <small style="font-size:80%;"><span locale="opr/overwrite/copying">Copying</span> <span class="owm-fc"></span> <span locale="opr/overwrite/files">files from</span> <span class="owm-srcdir"></span> <span locale="opr/overwrite/to">to</span> <span class="owm-destdir"></span></small>
                <p><span locale="opr/overwrite/dest">The destination has </span><span class="owm-fc"></span> <span locale="opr/overwrite/samename">files with the same names.</span></p>

                <div class="popupbuttons allowHover primary" onclick="changeOverwriteRule(0,true);">
                    <i class="checkmark icon"></i> <span locale="opr/overwrite/replace">Replace the files in the destination</span>
                </div>
                <div class="popupbuttons allowHover" onclick="changeOverwriteRule(1,true);">
                    <i class="reply icon"></i> <span locale="opr/overwrite/skip">Skip these files</span>
                </div>
                <div class="popupbuttons allowHover" onclick="changeOverwriteRule(2,true);">
                    <i class="undo icon"></i> <span locale="opr/overwrite/keep">Rename and keep the files</span>
                </div>
            </div>
        </div>
        <!-- Force delete confirmation box -->
        <div id="forceDeleteConfirmBox" class="popup" style="display:none;">
            <div class="popupheader">
                <i class="trash icon"></i> <span locale="opr/pre-remove/title">Permanently Remove Files</span>
                <div class="popupcloser" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i>
                </div>
            </div>
            <div class="popupcontent" style="padding:12px;">
                <p locale="opr/pre-remove/questions">Are you sure you want to remove these files <u>permanently?</u><br>This action is <u>irreversible</u>.</p>
                <div class="ui list deleteFilelist" style="max-height:350px;overflow-y:auto; ">

                </div>
                <div class="popupbuttons allowHover" style="background-color: #eb4034 !important;" onclick="forceDelete(true);";>
                <i class="trash icon"></i> <span locale="opr/pre-remove/confirm">Confirm</span>
                </div>
                <div class="popupbuttons allowHover" onclick="cancelForceDelete();">
                    <i class="remove icon"></i> <span locale="opr/pre-remove/cancel">Cancel</span>
                </div>

            </div>
        </div>

        <!-- Delete confirm box -->
        <div id="deleteConfirmBox" class="popup" style="display:none;">
            <div class="popupheader">
                <i class="recycle icon"></i> <span locale="opr/remove/title">Move files to Trash Bin</span>
                <div class="popupcloser" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i>
                </div>
            </div>
            <div class="popupcontent" style="padding:12px;">
                <p locale="opr/remove/question">Are you sure you want to move these files to trash bin?</p>
                <div class="ui list deleteFilelist" style="max-height:350px;overflow-y:auto; ">

                </div>
                <div class="popupbuttons allowHover" style="color: #2bbbdf !important;" onclick="deleteFile(true);";>
                    <i class="recycle icon"></i> <span locale="opr/remove/confirm">Move to Trash</span>
                </div>
                <div class="popupbuttons allowHover" style="background-color: #ff7a7a !important;" onclick="hideAllPopupWindows(); forceDelete();">
                    <i class="trash icon"></i> <span locale="opr/pre-remove/title">Delete Permanently</span>
                </div>
                <div class="popupbuttons allowHover" onclick="cancelDelete(); ">
                    <i class="remove icon"></i> <span locale="opr/remove/cancel">Cancel</span>
                </div>
            </div>
        </div>

        <!-- Rename tool box -->
        <div id="renameBox" class="popup" style="display:none;">
            <div class="popupheader">
                <i class="text cursor icon"></i> <span locale="opr/rename/title">Rename Files</span>
                <div class="popupcloser" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i>
                </div>
            </div>
            <div class="popupcontent" style="padding:12px;">
                <p locale="opr/rename/instruction">Enter the new filename for renaming. </p>
                <p class="multifileWarning"><i class="notice icon"></i> Other files will be named as file(#)</p>
                <div class="ui left icon small fluid input" style="margin-bottom:12px;">
                    <input type="text" class="orgfn" placeholder="Original Filename" readonly="true">
                    <i class="minus square icon" style="color:rgb(122, 176, 247)"></i>
                </div>
                <div class="ui left icon small fluid input" style="margin-bottom:12px;">
                    <input type="text" class="newfn" placeholder="New Filename" onkeydown="handleEnterKeyDown(event, function(){confirmRename(true);})">
                    <i class="add square icon" style="color:rgb(122, 176, 247)"></i>
                </div>
                <div class="popupbuttons allowHover primary"  onclick="confirmRename(true);";>
                <i class="checkmark icon"></i> <span locale="opr/rename/ok">OK</span>
                </div>
                <div class="popupbuttons allowHover" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i> <span locale="opr/rename/cancel">Cancel</span>
                </div>

            </div>
        </div>

        <!-- New File Dialog-->
        <div id="newFile" class="popup" style="display:none;">
            <div class="popupheader">
                <i class="add icon"></i> <span locale="opr/newfile/title">New File</span>
                <div class="popupcloser" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i>
                </div>
            </div>
            <div class="popupcontent" style="padding:12px;">
                <p locale="opr/newfile/instruction">Select a type of file to be created.</p>
                <div class="newfilelist" style="max-height:18em; overflow-y:scroll">
                    <div class="item newFileFormat" ext="php">No Item</div>
                </div>
                <p locale="opr/newfile/newempty">Or create an empty file with given filename:</p>
                <div class="ui left icon small fluid input" style="margin-bottom:12px;">
                    <input id="createNewFileName" type="text" placeholder="New Filename" onkeydown="handleEnterKeyDown(event, confirmNewFile);">
                    <i class="add square icon" style="color:rgb(122, 176, 247)"></i>
                </div>
                <p class="duplicateWarning" style="color:#CE5F58; display:none;"><i class="caution sign icon"></i> The given filename already exist.</p>
                <div class="popupbuttons allowHover primary"  onclick="confirmNewFile();";>
                    <i class="add icon"></i> <span locale="opr/newfile/create">Create</span>
                </div>
                <div class="popupbuttons allowHover" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i> <span locale="opr/newfile/cancel">Cancel</span>
                </div>
            </div>
        </div>

        <!-- New Folder Dialog-->
        <div id="newFolder" class="popup" style="display:none;">
            <div class="popupheader">
                <i class="folder icon"></i> <span locale="opr/newfolder/title">New Folder</span>
                <div class="popupcloser" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i>
                </div>
            </div>
            <div class="popupcontent" style="padding:12px;">
                <p locale="opr/newfolder/desc">Enter the new folder name to be created.</p>
                <div class="ui left icon small fluid input" style="margin-bottom:12px;">
                    <input id="createNewFolder" type="text" placeholder="New Folder Name" onkeydown="handleEnterKeyDown(event, function(){newFolder(true);});">
                    <i class="add square icon" style="color:rgb(122, 176, 247)"></i>
                </div>
                <p class="duplicateWarning" style="color:#CE5F58; display:none;"><i class="caution sign icon"></i> <span locale="opr/newfolder/alreadyExists">The given folder already exist.</span></p>
                <div class="popupbuttons allowHover primary"  onclick="newFolder(true);";>
                    <i class="add icon"></i> <span locale="opr/newfolder/create">Create</span>
                </div>
                <div class="popupbuttons allowHover" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i> <span locale="opr/newfolder/cancel">Cancel</span>
                </div>
            </div>
        </div>

        <!-- Share File Dialog-->
        <div id="shareFile" class="popup" style="display:none;">
            <div class="popupheader">
                <i class="external icon"></i> <span locale="opr/share/title">Share File</span>
                <div class="popupcloser" onclick="hideShare();">
                    <i class="remove icon"></i>
                </div>
            </div>
            <div>
                <iframe id="shareFileEmbedded" style="border: 0px solid transparent; width: 100%; height: 70vh;" allowtransparency="true">

                </iframe>
            </div>
            <div style="padding:12px;">
                <div class="ui divider"></div>
                <div id="sharingRemoveBtn" class="popupbuttons negative allowHover" onclick="removeSharing()">
                    <i class="remove icon"></i> <span locale="opr/share/remove">Remove Sharing</span>
                </div> 
                <div class="popupbuttons allowHover" onclick="hideShare();">
                    <i class="checkmark icon"></i> <span locale="opr/share/ok">OK</span>
                </div> 
            </div>
        </div>

        <!-- Open With Dialog-->
        <div id="openWith" class="popup" style="display:none;">
            <div class="popupheader">
                <i class="external icon"></i> <span locale="opr/openwith/title">Open File With</span>
                <div class="popupcloser" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i>
                </div>
            </div>
            <div class="popupcontent" style="padding:12px;">
               <p locale="opr/openwith/desc">Select a module from the list below:</p>
                <div id="openWithModuleList" class="ui segment" style="padding:0px;">
                    <div class="item selectable">
                        <div class="content" style="padding-left:12px;">
                            <div class="header" locale="opr/openwith/loading">Loading...</div>
                        </div>
                    </div>
                </div>
                <div class="openWithModule popupbuttons allowHover primary" onclick="openWithSelectedModule(this);";>
                    <i class="external icon"></i> <span locale="opr/openwith/openWithWebApp">Open with Selected Module</span>
                </div> 
                <div class="openWithModule popupbuttons allowHover" onclick="openFileWithModuleInNewTab(this);">
                    <i class="add icon"></i> <span locale="opr/openwith/openWithWebAppInNewWindow">Open in new tab</span>
                </div>
                <div class="popupbuttons allowHover vdonly" onclick="openRawFileInFloatWindow(this);">
                    <i class="window restore outline icon"></i> <span locale="opr/openwith/openInNewWindow">Open File directly in floatWindow</span>
                </div>
                <div class="popupbuttons allowHover" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i> <span locale="opr/openwith/cancel">Cancel</span>
                </div>
            </div>
        </div>

        <!-- Context Menu -->
        <div id="contextmenu" class="contextmenu" style="min-width:250px;">
            <div class="item" onclick="openViaButton();">
                <i class="folder open icon"></i> <span locale="contextmenu/open">Open</span>
            </div>
            <div class="item fileonly" onclick="openWith();">
                <i class="external icon"></i> <span locale="contextmenu/openWith">Open With</span>
            </div>
            <div class="item folderonly" onclick="openSelectedFolderInNewWindow();">
                <i class="external icon"></i> <span locale="contextmenu/openNewWindow">Open In New Window</span>
            </div>
            <!-- This is the vroot alternative new windows-->
            <div class="item vrootonly" onclick="openSelectedVroot();">
                <i class="external icon"></i> <span locale="contextmenu/openNewWindowVroot">Open In New Window</span>
            </div>
            <div class="item shareonly" onclick="openFileLocation();">
                <i class="folder outline icon"></i> <span locale="contextmenu/openFileLocation">Open File Location</span>
            </div>
            <div class="item singleObjectOnlyHide" onclick="shareFile();">
                <i class="share alternate icon"></i> <span locale="contextmenu/Share">Share</span>
            </div>
            <div class="item mobileonly" onclick="toggleCtrl();">
                <i class="mouse pointer icon"></i> <span locale="contextmenu/MuitSelect">Multi-select</span>
            </div>
            <div class="item" onclick="copy();">
                <i class="copy icon"></i> <span locale="contextmenu/copy">Copy</span>
                <span class="description">Ctrl + C</span>
            </div>
            <div class="item allowNoSelection" onclick="paste();">
                <i class="paste icon"></i> <span locale="contextmenu/paste">Paste</span>
                <span class="description">Ctrl + V</span>
            </div>
            <div class="item" onclick="cut();">
                <i class="cut icon"></i> <span locale="contextmenu/cut">Cut</span>
                <span class="description">Ctrl + X</span>
            </div>
            <div class="divider vroothide noSelectionOnly"></div>
            <div class="item noSelectionOnly" onclick="newfile();">
                <i class="file outline icon"></i>  <span locale="contextmenu/newFile">New File</span>
            </div>
            <div class="item noSelectionOnly" onclick="newFolder();">
                <i class="folder outline icon"></i> <span locale="contextmenu/newFolder">New Folder</span>
            </div>
            <div class="divider vroothide"></div>
            <div class="item noSelectionOnly" onclick="upload();">
                <i class="upload icon"></i>  <span locale="contextmenu/upload">Upload</span>
            </div>
            <div class="item" onclick="zipFile();">
                <i class="zip file icon"></i> <span locale="contextmenu/zip">Create Zip</span>
            </div>
            <div class="item zipFileOnly" onclick="unzipHere();">
                <i class="inbox icon"></i> <span locale="contextmenu/unzip">Unzip Here</span>
            </div>
            <div class="item" onclick="rename();">
                <i class="i cursor icon"></i> <span locale="contextmenu/rename">Rename</span>
            </div>
            <div class="item" onclick="deleteFile();">
                <i class="trash icon"></i> <span locale="contextmenu/delete">Delete</span>
            </div>
            <div class="item folderonly singleObjectOnlyHide" onclick="createDesktopShortcut();">
                <i class="external square icon"></i> <span locale="opr/shortcut/title">Create Shortcut on Desktop</span>
            </div>
            <div class="divider vroothide"></div>
            <div class="item noSelectionOnly" onclick="refreshList();">
                <i class="refresh icon"></i> <span locale="contextmenu/refresh">Refresh</span>
            </div>
            <div class="item" onclick="downloadFile();">
                <i class="download icon"></i> <span locale="contextmenu/download">Download</span>
            </div>
            <div class="item" onclick="showFileProperties();">
                <i class="info circle icon"></i> <span locale="contextmenu/properties">Properties</span>
            </div>
            <!-- This properties shows the currentDirectory properties instead of the selected file properties-->
            <div class="item noSelectionOnly" onclick="showCurrentDirectoryProperties();">
                <i class="ui info circle icon"></i> <span locale="contextmenu/properties">Properties</span>
            </div>
            <div class="item vrootonly" onclick="showSharesManager();">
                <i class="share alternate icon"></i> <span locale="contextmenu/sharemanager">Open Shares Manager</span>
            </div>
            <!-- This properties show the vroot properties -->
            <div class="item vrootonly" onclick="showVrootProperties();">
                <i class="ui info circle icon"></i> <span locale="contextmenu/properties">Properties</span>
            </div>
        </div>

        <!-- Upload Progress Bars-->
        <div id="uploadTab" class="ui segment" style="display:none;">
            <div class="statusBar">
                <i class="upload icon"></i><span id="uploadCount">0</span> <span locale="upload/count/uploading">Files</span> / <i class="wait icon"></i> <span id="waitingCount">0</span> <span locale="upload/count/pending">Files</span>
                <div class="hideUploadButton" onclick="toggleUploadList();">
                    <i class="caret down icon"></i>
                </div>
            </div>
            <div class="uploadList" id="uploadProgressList">
              
            </div>
            <br>
        </div>

        <!-- Confirm Exit -->
         <!-- Open With Dialog-->
         <div id="confirmExit" class="popup" style="display:none;">
            <div class="popupheader">
                <i class="external icon"></i> <span locale="opr/confirmclose/title">Confirm Exit</span>
                <div class="popupcloser" onclick="hideAllPopupWindows();">
                    <i class="remove icon"></i>
                </div>
            </div>
            <div class="popupcontent" style="padding:12px;">
                <p locale="opr/confirmclose/desc">This file manager instance is currently uploading file to server. Closing this instance will cancel the upload tasks. <br>
                    <b>Confirm Exit?</b></p>
                <div class="popupbuttons negative allowHover" onclick="ao_module_closeHandler(); hideAllPopupWindows();">
                    <i class="trash icon"></i> <span locale="opr/confirmclose/cancelAndExit">Cancel Upload and Exit</span>
                </div>
                <div class="popupbuttons allowHover" onclick="hideAllPopupWindows();">
                    <i class="checkmark icon"></i> <span locale="opr/confirmclose/continue">Continue Upload</span>
                </div>
            </div>
        </div>

           
        <script>
            let directorySidebarWidth = 250; //Width of the sidebar
            let sideBarShown = true; //Indicate if sidebar is shown
            let rootDirs = [];  //Storage location for rootDirs
            let currentTheme = "whiteTheme"; //Default theme
            let viewMode = "list"; //Viewmode, support {list, grid, detail}
            let sortMode = "default"; //Sortmode, support {default, reverse, smallToLarge, largeToSmall, mostRecent, leastRecent}
            let currentPath = "user:/"
            let viewHistory = []; //View history
            let enableBetaFilename = false; //Enable beta filename conversion from "inith..." to "normal"
            let currentFilelist = []; //The current file list in the currentPath
            let currentPathHash = "";   //The folder content hash
            let enableAutoRefresh = true; //Enable directory updates on file change
            let filesIconTheme = "default";

            //File operations
            let clipboard = []; //System clipboard
            let cutMode = false; //If set to true, this is cut mode. Else copy mode
            let useLocalstorage = lscheck();
            let overwriteMode = "keep"; //Overwrite mode, support {skip, overwrite, keep}
            let thumbRenderWebSocket = null;
            let pathInputMode = false;
            let renameMode = false;

            //Searching related
            let searchCaseSensitive = false;
            let viewModeBeforeSearch = "list";
            let searchMode = false;
            let hotSearchBuffer = "";
            let hotSearchTimer = null;
            let hotSearchOffsetIndex = 0;
            let propertiesView = false; //Enable viewing properties on the right sidebar

            //Keypress listeners
            let ctrlHold = false;
            let shiftHold = false;
            let lastClickedElement = undefined;

            //Upload related
            let uploadingFileCount = 0;
            let maxConcurrentUpload = 4; //Maxmium number of oncurrent upload
            let uploadPendingList = []; //Upload pending queue for mass upoad
            let lowMemoryMode = true;   //Upload with low memory mode channel
            let largeFileCutoffSize = 8192 * 1024 * 1024; //Any file larger than this size is consider "large file", default to 8GB
            let uploadFileChunkSize = 1024 * 512; //512KB, 4MB not working quite well on slow network
            let postUploadModeCutoff = 25 * 1048576; //25MB, files smaller than this will upload using POST Mode

            //File Sharing related
            let shareEditingObject = "";
            let shareEditingUUID = "";

            //System Information
            let systecontextmenumUUID = "";
            let systemIP = "";

            //Browser detection
            let isMobile = window.mobilecheck();
            let isChromium = window.chrome;
            let isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
            let isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
            let isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

            //Intiiation functions
            $(document).ready(function(){
                $("#contextmenu").css("display", "hidden");
                if (applocale){
                    //Applocale found. Do localization
                    applocale.init("../locale/file_explorer.json", function(){
                        applocale.translate();
                        initRootDirs();
                        initSystemInfo();
                        initUploadMode();
                        $(".dropdown").dropdown();
                        $("#sortingMethodSelector").dropdown("set selected", sortMode);
                        updateSelectedObjectsCount();
                        initWindowSizes(false);
                    });
                }else{
                    //Applocale not found. Is this a trim down version of ArozOS?
                    applocale = {
                        getString: function(key, original){
                            return original;
                        }
                    }
                    initRootDirs();
                    initSystemInfo();
                    initUploadMode();
                    $(".dropdown").dropdown();
                }
           
                if (isMobile){
                    //Mobile css adjustment
                    sideBarShown = false;
                    $("#directorySidebar").hide();
                    $("#directorySidebar").css("width",window.innerWidth + "px");
                    $("body").css("overflow","hidden");
                    $("#navibar").addClass("mobile");
                    directorySidebarWidth = window.innerWidth;
                    $("#folderView").css({
                        "padding-right":"1em",
                        "padding-left":"1em",
                        "padding-top":"1em",
                    });

                    //Move the sort menu into the desktop address bar gap
                    $(".viewportBtns").addClass("mobile");
                    $(".addressBar").append($(".viewportBtns"));

                    //Move the sorting dropdown to sidebar
                    $("#mobileSortDropdown").append($("#sortingMethodSelector"));

                    $(".desktopOnly").hide();
                    $(".mobileOnly").show();
                }else{
                    $(".mobileOnly").hide();
                    $(".desktopOnly").show();
                }
                //Initialize view mode buttons
                updateViewmodeButtons();
                loadListModeFromDB();

                //Initialize system theme
                loadPreference("file_explorer/theme",function(data){
                    if (data.error === undefined){
                        if (data == "darkTheme"){
                            toggleDarkTheme();
                        }else{
                            //White theme
                        
                        }
                    }
                });

                //Initialize properties view
                if (localStorage.getItem("file_explorer/viewProperties") == "true"){
                    $("#togglePropertiesViewBtn").click();
                }


                if (window.location.hash != ""){
                    //Check if the hash is standard open protocol. If yes, translate it
                    if (ao_module_loadInputFiles() === null){
                        //Window location hash set. List the desire directory
                        currentPath = window.location.hash.substring(1,window.location.hash.length);
                        if (currentPath.substring(currentPath.length -1) != "/"){
                            currentPath = currentPath + "/";
                        }
                        currentPath = decodeURIComponent(currentPath);
                        loadListModeFromDB(function(){
                            listDirectory(currentPath);
                        });
                        
                    }else{
                        //This is ao_module load file input. Handle the file opening
                        var filelist = ao_module_loadInputFiles();
                        if (filelist.length > 0){
                            filelist = filelist[0];
                            //Check if this is folder or file. Only opendir when it is folder
                            //Updates 27-12-2020: Open folder and highlight the file if it is file
                            if (filelist.filename.includes(".") == false){
                                //Try to open it and overwrite the hash to filesystem hash
                                loadListModeFromDB(function(){
                                    listDirectory(filelist.filepath);
                                });
                            }else{
                                //File. Open its parent folder and highlight the target file if exists
                                var parentdir = filelist.filepath.split("/");
                                let focusFilename = JSON.parse(JSON.stringify(filelist.filename));
                                parentdir.pop();
                                parentdir = parentdir.join("/");
                                loadListModeFromDB(function(){
                                    listDirectory(parentdir, function(){
                                        if (focusFilename != ""){
                                            //Timeout to give the DOM time to render
                                            //DO NOT REPLACE THIS WITH listDirectoryAndHighlight
                                            //Additional delay are required on page load
                                            setTimeout(function(){
                                                focusFileObject(focusFilename);
                                            }, 300);
                                            
                                        }
                                    })
                                });
                            }
                        }
                    }
                }else{

                    //Initialized directory views
                    loadListModeFromDB(function(){
                        listDirectory(currentPath);
                    });
                }
                

                
                
                //Create a timer to check change in current folder
                setInterval(function(){
                    if (enableAutoRefresh == false){
                        return;
                    }
                    let currentPagePath = currentPath;
                    getDirHash(function(hash){
                        if (hash.error !== undefined){
                            //Something went wrong. Ignore this request
                            console.log(hash.error)
                        }else{
                            //Check if the hash match with the last hash && user is still on the same page
                            if (hash != currentPathHash && currentPagePath == currentPath){
                                //console.log(currentPathHash, hash);
                                refreshList();
                                currentPathHash = hash;
                                if (currentPath == "user:/"){
                                    //Reload the User root folder list
                                    initRootDirs();
                                }
                            }
                        }

                    });
                }, 5000);


                //Update the window sizes for special cases
                if (window.innerWidth < 620 && !isMobile){
                    toggleSidebar(false);
                }
                initWindowSizes(false);
            });

            //END OF INIT FUNCTIONS

            //Get the system ID and ip address from the system id services
            function initSystemInfo(){
                $.get("../../system/id/requestInfo",function(data){
                    if (data.error !== undefined){
                        msgbox("red remove", data.error);
                    }else{
                        systemUUID = data.SystemUUID;
                        systemIP = data.IpAddress;
                    }
                });
            }

            //Initiate the sidebar contents 
            function initRootDirs(){
                //Load user directories
                $.ajax({
                    url:"../../system/file_system/listRoots?user=true",
                    success: function(data){
                        $("#userroot").html("");
                        for (var i =0; i < data.length; i++){
                            var thisRootObject = data[i];
                            if (thisRootObject.IsDir == true && !(thisRootObject.Filename == ".cache" || thisRootObject.Filename == ".trash")){
                                //Files will not be listed in the root directory list
                                var specifcRootInfo = getUserRootIcons(thisRootObject.Filename);
                                var icon = specifcRootInfo[0];
                                var displayName = specifcRootInfo[1];
                                var vpath = thisRootObject.Filepath;
                                $("#userroot").append(`<div class="dir item userrootfolder" filepath="${vpath}" type="folder" onclick="openthis(this);"><i class="${icon} rightmargin icon"></i> ${displayName}</div>`);
                            }
                        }
                    }   
                });

                //Load other storage devices
                $.ajax({
                    url:"../../system/file_system/listRoots",
                    success: function(data){
                        $("#storageroot").html("");
                        for (var i =0; i < data.length; i++){
                            var thisRoot = data[i];
                            var displayName = thisRoot.RootName;
                            var rootPath = thisRoot.RootPath;
                            $("#storageroot").append(`<div class="dir item vroot" filepath="${rootPath}" type="folder" rootname="${displayName}" onclick="openthis(this);"><i class="disk outline rightmargin icon"></i> ${displayName} (${rootPath})</div>`);
                        }
                        highlightCurrentRoot();
                    }
                });
            }

            function highlightCurrentRoot(){
                //Highlight the target vroot name on the side bar
                $(".vroot.active").removeClass("active");
                $(".vroot").each(function(){
                   let rootname = $(this).attr("filepath");
                    if ((currentPath.toLowerCase()).startsWith((rootname.toLowerCase()))){
                        //This is the root we are currently in
                        $(this).addClass("active");
                    }
                });
            }
          

            function getUserRootIcons(foldername){
                var icon = "folder open";
                var name = foldername;
                foldername = foldername.toLowerCase();
                if (foldername == "desktop"){
                    icon = "computer";
                    name = applocale.getString("sidebar/vroot/desktop", name);
                }else if (foldername == "document"){
                    icon = "file text outline";
                    name = applocale.getString("sidebar/vroot/document", name);
                }else if (foldername == "music" || foldername == "audio"){
                    icon = "music";
                    name = applocale.getString("sidebar/vroot/music", name);
                }else if (foldername == "photo" || foldername == "picture"){
                    icon = "image";
                    name = applocale.getString("sidebar/vroot/photo", name);
                }else if (foldername == "video" || foldername == "film"){
                    icon = "video";
                    name = applocale.getString("sidebar/vroot/video", name);
                }else if (foldername == "trash" || foldername == "bin" || foldername == "rubbish"){
                    icon = "trash"
                    name = applocale.getString("sidebar/vroot/trash", name);
                }else if (foldername == "download"){
                    icon = "download"
                    name = applocale.getString("sidebar/vroot/download", name);
                }else if (foldername == "www" || foldername == "web" || foldername == "mysite"){
                    icon = "globe"
                    name = applocale.getString("sidebar/vroot/web", name);
                }else if (foldername == "model"){
                    icon = "cube"
                    name = applocale.getString("sidebar/vroot/model", name);
                }else if (foldername == "appdata"){
                    icon = "code"
                    name = applocale.getString("sidebar/vroot/appdata", name);
                }
                return [icon, name];
            }

            // ============================== FOLDER LISTING FUNCTIONS ====================
            function listDirectory(path, callback=undefined, recordUndo=true){
                enableAutoRefresh = false;
                var recordPreviousPage = true;
                if (recordUndo == false){
                    recordPreviousPage = false;
                }

                if (searchMode){
                    hideSearchBar(true);
                }

                if (pathInputMode){
                    hideManualOpenPathInput();
                }

                if (isMobile && ctrlHold){
                    exitMultiSelectMode();
                }

                //Backup the current selected files if it is an refresh operation
                let selectedFiles = [];
                let currentScrollTop = JSON.parse(JSON.stringify($("#folderView").scrollTop()));
                if (path == currentPath){
                    $(".fileObject.item.selected").each(function(){
                        selectedFiles.push($(this).attr("filename"));
                    });

                    //Set record histroy to false on refresh
                    recordPreviousPage = false;
                }
               
                //Always pad slash to the end of path
                if (path.substring(path.length - 1) != "/"){
                    path = path + "/";
                }

                //Clean the path if there are any malformat
                if (path.indexOf("//") != -1){
                    path = path.split("//").join("/");
                }

                if (recordPreviousPage){
                    viewHistory.push(currentPath);
                }
               
                window.location.hash = path;
                updatePathDisplay(path);
                currentPath = path;

                //Update floatWindow title if exists
                if (ao_module_virtualDesktop){
                    var tmp = path.split("/");
                    tmp.pop();
                    ao_module_setWindowTitle(applocale.getString("title/title", "File Manager") + " - " + tmp.pop());
                }

                //Check if there are parent path for curret path
                if (checkIfParentDirExists(currentPath)){
                    $("#ppbtn").removeClass("disabled");
                }else{
                    $("#ppbtn").addClass("disabled");
                }
                if (viewHistory.length < 1){
                    $("#backbtn").addClass("disabled");
                }else{
                    $("#backbtn").removeClass("disabled");
                }

                //Add loading screen to the folderlists and fileList
                $("#fileList").html("");
                let loaderClass = "inverted";
                if (currentTheme == "darkTheme"){
                    loaderClass = "";
                }
                $("#folderList").html(`<div style="height: 100px;">
                    <div class="ui active ${loaderClass} dimmer" style="z-index: 95;">
                        <div class="ui text loader">${applocale.getString("message/loading", "Loading")}</div>
                    </div>
                </div>`);
                
                $(".userroot.active").removeClass('active');
                
                //Highlight new path coot
                highlightCurrentRoot();
               
                //Get sort mode from server side
                let loadStartPath = currentPath;
                $.ajax({
                    url: "../../system/file_system/sortMode",
                    metod: "POST",
                    data: {opr: "get", folder: currentPath},
                    success: function(data){
                        if (data.error == undefined){
                            sortMode = data;
                        }
                        $("#sortingMethodSelector").dropdown("set selected", sortMode);
                        //Start listdir event
                        $.ajax({
                            url: "../../system/file_system/listDir",
                            method: "POST",
                            data: {dir: decodeURIComponent(path), sort: sortMode},
                            success: function(data){
                                //Parse the filelist into global variable
                                currentFilelist = [];
                                if (data === null){
                                    //There is nothing in this folder.
                                    $("#folderList").hide();
                                    $("#fileList").hide();
                                    if (callback !== undefined){
                                        callback();
                                    }
                                    return;
                                }

                                if (currentPath != loadStartPath){
                                    //Use switch to another path before the load finish. Do not render
                                    return;
                                }

                                if (data.error !== undefined){
                                    //Parse path error. Try to refresh the page
                                    if (data.error.length >= "Redirect:".length && data.error.substr(0,9) == "Redirect:"){
                                        var redirectAction = data.error.substr(9).trim();
                                        if (redirectAction == "parent"){
                                            var pdir = currentPath.split("/");
                                            pdir.pop(); pdir.pop();
                                            pdir = pdir.join("/");
                                            currentPath = pdir;
                                            listDirectory(currentPath);
                                        }else if (redirectAction == "root"){
                                            var currentRoot = currentPath.split("/").shift();
                                            listDirectory(currentRoot);
                                        }else if (redirectAction == "userroot"){
                                            listDirectory("user:/")
                                        }else{
                                            //Try to breakdown the redirection path
                                            listDirectory(redirectAction, undefined, false);
                                        }
                                        return
                                    }

                                    
                                    //Check if it is already rooted and no more parent ahead
                                    if (currentPath == ""){
                                        currentPath = "user:/";
                                    }
                                    
                                    //Print folder not found exception
                                    $("#folderList").show();
                                    $("#folderList").html(`<div class="ui basic segment">
                                        <div class="ui header themed">
                                            <i class="remove icon"></i> <span>${applocale.getString("message/folderCannotOpen","This Folder Cannot Be Opened")}</span>
                                            <div class="sub header" style="margin-top:12px;">${applocale.getString("message/folderCannotOpen/codedesc","The server return the following error message:")} <br><code>${data.error.toUpperCase()}</code><br>
                                                ${new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'})}</div>
                                        </div>
                                    </div>`);
                                    $("#fileList").hide();

                                    enableAutoRefresh = false;
                                    return;
                                }else{
                                    enableAutoRefresh = true;
                                    //Filelist returned. Render it
                                    renderDirectory(data,function(){
                                        //Restore the selected file list
                                        $(".fileObject.item").each(function(){
                                            for (var i = 0; i < selectedFiles.length; i++){
                                                var thisFilename = selectedFiles[i];
                                                if (thisFilename == $(this).attr("filename")){
                                                    $(this).addClass("selected");
                                                }
                                            }
                                        });

                                        //Restore the previous scroll position
                                        $("#folderView").scrollTop(currentScrollTop);
                                        
                                        //Perform the callback
                                        if (callback !== undefined){
                                            callback();
                                        }

                                        enableAutoRefresh = true;
                                    });
                                }
                            },
                            error: function(){
                                enableAutoRefresh = true;
                            }
                        });
                    },
                    error: function(){
                        enableAutoRefresh = true;
                    }
                });
            }

            function listDirectoryAndHighlight(path, filenameToHighlight = ""){
                listDirectory(path, function(){
                    if (filenameToHighlight != ""){
                        //Timeout to give the DOM time to render
                        setTimeout(function(){
                            focusFileObject(filenameToHighlight);
                        }, 100);
                        
                    }
                })
            }

            //Render filelist --> Convert a file list object into the visable form of file list
            function renderDirectory(filelist, callback=undefined){
                var data = filelist;
                $("#fileList").html("");
                $("#folderList").html("");
                //Build the css strcture of the list
                if (viewMode == "list"){

                }else if (viewMode == "details"){
                    //Append the table structure to the corrisponding elements
                    $("#folderList").append(`<table class="ui very basic unstackable table detailstable"  style="padding-right: 2em;">
                        <thead>
                            <tr>
                                <th style="white-space: nowrap !important;"><span class="foldercounter"></span>${applocale.getString("view/details/folders", " Folders")}</th>
                                <th style="white-space: nowrap !important;">${applocale.getString("view/details/modTime", "Last Modification")}</th>
                                <th style="white-space: nowrap !important;">${applocale.getString("view/details/shared", "Shared")}</th>
                            </tr>
                        </thead>
                        <tbody class="folderDetailList detailTableContent">
                            
                        </tbody>
                    </table>`);
                    $("#fileList").append(`<table class="ui very basic compact unstackable table detailstable" style="padding-right: 2em;">
                        <thead>
                            <tr>
                                <th><span class="filecounter"></span>${applocale.getString("view/details/files", " Files")}</th>
                                <th style="white-space: nowrap !important;">${applocale.getString("view/details/ext", "Extension")}</th>
                                <th style="white-space: nowrap !important;">${applocale.getString("view/details/size", "Filesize")}</th>
                                <th style="white-space: nowrap !important;">${applocale.getString("view/details/modTime", "Last Modification")}</th>
                                <th style="white-space: nowrap !important;">${applocale.getString("view/details/shared", "Shared")}</th>
                            </tr>
                        </thead>
                        <tbody class="fileDetailList detailTableContent">
                            
                        </tbody>
                    </table>`);
                }else if (viewMode == "grid"){
                  
                }
            
                var files = [];
                var folders = [];
                for (var i =0; i < data.length; i++){
                    if (data[i].IsDir == true){
                        //This is folder
                        folders.push(data[i]);
                    }else{
                        //This is file
                        files.push(data[i]);
                    }
                    currentFilelist.push(JSON.parse(JSON.stringify(data[i].Filename)));
                }
                //Define the grid size for the interface
                var gridSize = 150 ;

                if (isMobile){
                    //Update 3/5/2021: Optimize the width calculation method to best fit
                    //A hack to align the divs to center of the container
                    $("#folderView").attr("align", "center");
                    $("#folderList").attr("align", "left");
                    $("#fileList").attr("align", "left");

                    //Calculate the best width to fit all the grids
                    var bestCount = Math.floor(parseFloat($("#folderView").width()) / parseFloat(gridSize));
                    var bestOffset = $("#folderView").width() % gridSize;
                    gridSize = gridSize + (bestOffset / bestCount) - (window.innerWidth - $("#folderView").width()) / bestCount;
                }
                
                //List all folders
                for (var i =0; i < folders.length; i++){
                    var filename = folders[i].Filename;
                    var filepath = folders[i].Filepath;
                    var realpath = folders[i].Realpath;
                    var isDir = folders[i].IsDir;
                    var filesize = folders[i].Filesize;
                    var Displaysize = folders[i].Displaysize;
                    var isShared = folders[i].IsShared;
                    var modTime = folders[i].ModTime;
                    var ext = getExtFromPath(filepath);
                    //var icon = ao_module_utils.getIconFromExt(ext);
                    var icon = "folder";
                    var shareicon = "";
                    if (isShared == true){
                        shareicon = `<button class="sharebtn" onclick='handleShareFilebuttonClick(event, this);' style="margin-left: 0; height: 16px;">
                            <i class='share alternate icon'></i>
                        </button>`
                    }
                    if (viewMode == "list"){
                        var textclass = "normal object";
                        var displayName = filename;
                        try{
                            //Try to decode it using ArozOS Beta naming scheme
                            if (enableBetaFilename && ao_module_codec.decodeHexFoldername(displayName) != displayName){
                                displayName = ao_module_codec.decodeHexFoldername(displayName, false);
                                textclass = "hex foldername";
                            }
                        }catch(ex){
                            //Codec decode failed. Fallback to default name

                        }
                       
                        $("#folderList").append(`<div class="fileObject item" draggable="true" ondragstart="onFileObjectDragStart(this,event);" ondrop="dropToFolder(event)" ondragover="allowDrop(event)" fileID="${i}" filename="${filename}" filepath="${filepath}" ondblclick="openthis(this,event,true);" type="folder">
                            <span style="display:inline-block !important;word-break: break-all; width:100%;" class="${textclass}">
                                <i class="${icon} icon" style="margin-right:12px; color:#eab54e;"></i>  <span class="filename">${displayName}</span> ${shareicon}
                            </span></div>`);
                    }else if (viewMode == "grid"){
                        var displayName = JSON.parse(JSON.stringify(filename));
                        var textclass = "normal object";
                         try{
                             //Try to decode it using ArozOS Beta naming scheme
                            if (enableBetaFilename && ao_module_codec.decodeHexFoldername(displayName) != displayName){
                                displayName = ao_module_codec.decodeHexFoldername(displayName, false);
                                textclass = "hex foldername";
                            }
                        }catch(ex){
                            //Codec decode failed. Fallback to default name
                            
                        }
                        if (displayName.length > 16){
                            displayName = displayName.substring(0,16) + "...";
                        }
                        $("#folderList").append(`
                        <div class="fileObject card" draggable="true" ondragstart="onFileObjectDragStart(this,event);" ondrop="dropToFolder(event)" ondragover="allowDrop(event)" fileID="${i}" filename="${filename}" filepath="${filepath}" ondblclick="openthis(this,event,true);" type="folder" style="width:${gridSize}px; display:inline-block !important;vertical-align:top; height:15em; margin-top:0px !important; overflow:hidden;">
                            <div class="image" style="text-align: center;">
                                <img draggable="true"ondragstart="disableDrag(event);" src="../../img/desktop/files_icon/${filesIconTheme}/folder.png" style="height: 148px; width: 148px; display: inline-block;">
                                <div class="shareOverlay ${isShared?"visible":""}">${shareicon}</div>
                            </div>
                            <div class="content" style="font-size: 12px;">
                                <div class="header ${textclass} filename" title="${filename}">${displayName}</div>
                            </div>
                            
                        </div>`);
                    }else if (viewMode == "details"){
                        let isSharedIcon = '<i class="ui grey remove icon" style="margin-left: 6px;"></i>';
                        if (isShared){
                            isSharedIcon = shareicon;
                        }

                        //Convert the unix timestamp to datetime
                        var date = new Date(modTime * 1000);
                        $("#folderList").find(".folderDetailList").append(`<tr class="fileObject details" draggable="true" ondragstart="onFileObjectDragStart(this,event);" ondrop="dropToFolder(event)" ondragover="allowDrop(event)" fileID="${i}" filename="${filename}" filepath="${filepath}" ondblclick="openthis(this,event,true);" type="folder">
                            <td style="word-break: break-all; text-overflow: ellipsis !important; min-width: 250px;"><i class="${icon} icon" style="margin-right:12px; color:#eab54e;"></i> <span class="filename">${filename}</span></td>
                            <td class="light-text">${date.toLocaleDateString("default") + " " + date.toLocaleTimeString("default")}</td>
                            <td>${isSharedIcon}</td>
                        </tr>`);
                    }
                }

                if (folders.length == 0){
                    $("#folderList").hide();
                }else{
                    $("#folderList").show();
                }

            
                //List all files
                let fl = folders.length; //DO NOT REMOVE THIS
                for (var i =0; i < files.length; i++){
                    var filename = files[i].Filename;
                    var filepath = files[i].Filepath;
                    var realpath = files[i].Realpath;
                    var filesize = files[i].Filesize;
                    var Displaysize = files[i].Displaysize;
                    var isShared = files[i].IsShared;
                    var modTime = files[i].ModTime;
                    var ext = getExtFromPath(filepath);
                    
                    var icon = "file outline";
                    if (ext == ""){
                        icon = "file outline";
                    }else if (ext == "shortcut"){
                        //Use the default shortcut icon
                        icon = ao_module_utils.getIconFromExt(ext);

                        //Check if the shortcut object exists
                        if (files[i].Shortcut != undefined && files[i].Shortcut != null){
                            icon = files[i].Shortcut.Icon;
                        }

                    }else{
                        icon = ao_module_utils.getIconFromExt(ext);
                    }

                    var shareicon = "";
                    if (isShared){
                        shareicon = `<button class="sharebtn" onclick='handleShareFilebuttonClick(event, this);' style="margin-left: 0px; height: 16px;">
                            <i class='share alternate icon'></i>
                        </button>`
                    }
                    
                    var fileType = "file";
                    if (ext == "shortcut"){
                        fileType = "shortcut";
                    }

                    if (viewMode == "list"){
                        var displayName = filename;
                        var textclass = "normal object";

                        if (ext == "shortcut"){
                            //This is a shortcut file
                            displayName = files[i].Shortcut.Name;

                            //Adjust the icon based on its shortcut ype
                            switch(files[i].Shortcut.Type){
                                case "folder":
                                    icon = "blue folder";
                                    break;
                                case "module":
                                    icon = "blue play circle";
                                    break;
                                default: 
                                    icon = "external";
                            }
                        }

                        if (enableBetaFilename){
                            decodedName = ao_module_codec.decodeUmFilename(displayName);
                            if (decodedName != displayName){
                                displayName = decodedName;
                                textclass = "um filename";
                            }
                            filename = ao_module_codec.decodeUmFilename(filename);
                        }
                        $("#fileList").append(`<div class="fileObject item" draggable="true" ondragstart="onFileObjectDragStart(this,event);"  fileID="${fl + i}"  filename="${filename}" filepath="${filepath}" ondblclick="openthis(this,event, true);"  type="${fileType}" filesize="${filesize}" displaysize="${Displaysize}">
                            <span style="display:inline-block !important;word-break: break-all;text-overflow: ellipsis !important;overflow: hidden;" class="${textclass}">
                                <i class="${icon} icon" style="margin-right:12px;"></i>  
                                <span class="filename">${displayName}</span>  ${shareicon}
                            </span>
                        </div>`);
                    }else if (viewMode == "grid"){
                        //Update the icon path depends on the type of file
                        var imagePath = "../../img/desktop/files_icon/" + filesIconTheme + "/" + icon + ".png";
                        var displayName = JSON.parse(JSON.stringify(filename));
                        if (ext == "shortcut"){
                            //This is a shortcut file. Treat it specially
                            if (icon.includes("http://") || icon.includes("https://")){
                                //Direct path. Do not add relative prefix
                                imagePath = icon;
                            }else{
                                imagePath = "../../" + icon;
                            }
                            displayName = files[i].Shortcut.Name;
                            ext = files[i].Shortcut.Type;
                            ext = ext.charAt(0).toUpperCase() + ext.slice(1);
                        }else{
                            ext = "." + ext;
                        }

                        var textclass = "normal object";
                        if (enableBetaFilename){
                            decodedName = ao_module_codec.decodeUmFilename(displayName);
                            if (decodedName != displayName){
                                textclass = "um filename";
                                displayName = decodedName;
                            }
                            filename = ao_module_codec.decodeUmFilename(filename);
                        }
                        
                        if (displayName.length > 20){
                            displayName = displayName.substring(0,20) + "...";
                        }

                       
                        
                        $("#fileList").append(`
                        <div class="fileObject card" draggable="true" ondragstart="onFileObjectDragStart(this,event);" fileID="${fl + i}" filename="${filename}" filepath="${filepath}" ondblclick="openthis(this,event);" type="${fileType}" style="width:${gridSize}px; display:inline-block !important;vertical-align:top; height:20em;  margin-top:0px !important;  overflow:hidden;">
                            <div class="image" style="text-align: center !important;">
                                <img draggable="true"ondragstart="disableDrag(event);" style="height: 148px; width: 148px; display:inline-block;" src="${imagePath}">
                                <div class="shareOverlay ${isShared?"visible":""}">${shareicon}</div>
                            </div>
                            <div class="content">
                                <div class="header ${textclass}" title="${filename}" style="text-overflow: ellipsis; font-size: 100%"><span class="filename">${displayName}</span></div>
                                <div class="meta">
                                    <div>${ext}</div>
                                </div>
                                <div class="description">
                                    ${Displaysize}
                                </div>
                            </div>
                        </div>
                        `);
                    }else if (viewMode == "details"){
                        if (ext == "shortcut"){
                            //This is a shortcut file
                            displayName = files[i].Shortcut.Name;

                            //Adjust the icon based on its shortcut ype
                            switch(files[i].Shortcut.Type){
                                case "folder":
                                    icon = "blue folder";
                                    break;
                                case "module":
                                    icon = "blue play circle";
                                    break;
                                default: 
                                    icon = "blue external";
                            }
                        }

                        let isSharedIcon = '<i class="ui grey remove icon" style="margin-left: 4px;"></i>';
                        if (isShared){
                            isSharedIcon = shareicon;
                        }

                        var date = new Date(modTime * 1000);

                        $("#fileList").find(".fileDetailList").append(`<tr class="fileObject details" draggable="true" ondragstart="onFileObjectDragStart(this,event);" ondrop="dropToFolder(event)" ondragover="allowDrop(event)" fileID="${fl + i}" filename="${filename}" filepath="${filepath}" ondblclick="openthis(this,event,true);" type="file">
                            <td style="word-break: break-all; text-overflow: ellipsis !important; min-width: 250px;"><i class="${icon} icon" style="margin-right:12px;"></i>  <span class="filename">${filename}</span></td>
                            <td class="light-text">${ext}</td>
                            <td class="light-text">${Displaysize}</td>
                            <td class="light-text">${date.toLocaleDateString("default") + " " + date.toLocaleTimeString("default")}</td>
                            <td>${isSharedIcon}</td>
                        </tr>`);
                    }
                }
                if (files.length == 0){
                    $("#fileList").hide();
                }else{
                    $("#fileList").show();
                }

                bindFileObjectEvents();
                currentFilelist.sort();
                //Update the filelist hash
                enableAutoRefresh = false;
                getDirHash(function(hash){
                    currentPathHash = hash;
                    enableAutoRefresh = true;
                });

                //Finish up the rendering
                if (viewMode == "list"){

                }else if (viewMode == "details"){
                    //Load the statistic of the folder details
                    $("#folderList").find(".foldercounter").text(folders.length);
                    $("#fileList").find(".filecounter").text(files.length);
                }else if (viewMode == "grid"){
                    //If viewmode is grid, load file thumbnails
                    startThumbnailLoader();
                }

                //Update the no. of items in the viewport
                updateSelectedObjectsCount();

                if (callback !== undefined){
                    callback();
                }
            }

            function startThumbnailLoader(){
                let path = currentPath;
                let protocol = "wss://";
                if (location.protocol !== 'https:') {
                    protocol = "ws://";
                }

                var port = window.location.port;
                if (window.location.port == ""){
                    if (location.protocol !== 'https:') {
                        port = "80";
                    }else{
                        port = "443";
                    }
                }

                thumbRenderWebSocket = new WebSocket(protocol + window.location.hostname + ":" + port + "/system/file_system/handleCacheRender?folder=" + encodeURIComponent(path));

                thumbRenderWebSocket.onopen = function(e) {

                };

                thumbRenderWebSocket.onmessage = function(event) {
                    //Find the correct file in the current directory and place its image
                    if (path == currentPath){
                        var thumbData = JSON.parse(event.data);
                        $(".fileObject").each(function(){
                            if (thumbData[1].length > 0){
                                //Extract image type from base64
                                let ext = getThumbnailExtensionFromBase64String(thumbData[1]);
                                //Put the image data to image element
                                if ($(this).attr("filename") == thumbData[0]){
                                    $(this).find("img").attr("src","data:image/" + ext + ";base64," + thumbData[1]);
                                }
                            }
                          
                        });
                    }
                };


                thumbRenderWebSocket.onclose = function(event) {
                    //Transfer ended
                };

                thumbRenderWebSocket.onerror = function(error) {
                    //Cache render on websocket failed. Fallback to AJAX request
                    console.log("Cannot connect to WebSocket cache renderer. Falling back to AJAX request");
                    startFallbackThumbnailLoader();
                };
            }

            function getThumbnailExtensionFromBase64String(base64String){
                let ext = "jpg";
                if (typeof base64String === 'string' || base64String instanceof String){
                    let tid = base64String.charAt(0);
                    if (tid == "i"){
                        ext = "png";
                    }else if (tid == "R"){
                        ext = "gif";
                    }else if (tid == "U"){
                        ext = "webp";
                    }
                }else{
                    //Not string
                }
                
                return ext;
            }

            
            function startFallbackThumbnailLoader(){
                let startingCurrentDir = currentPath;
                let fallbackRenderList = [];
                $(".fileObject").each(function(){
                    let filepath = $(this).attr("filepath");
                    let targetDOM = $(this);
                    if ($(this).attr("type") != "folder"){
                        fallbackRenderList.push([filepath, targetDOM]);
                    }
                });

                doThumbnailSequentialLoading(startingCurrentDir, fallbackRenderList, 0);
            }

            function doThumbnailSequentialLoading(startingCurrentDir, renderlist, index){
                if (renderlist[index] == undefined){
                    //Starting index out of range
                    return;
                }
                let filepath = renderlist[index][0];
                let targetDOM = renderlist[index][1];
                $.ajax({
                    url: "../../system/file_system/loadThumbnail",
                    data: {vpath: filepath},
                    success: function(data){
                        if (startingCurrentDir == currentPath){
                            //User still not changed page
                            let ext = getThumbnailExtensionFromBase64String(data);
                            if (data.error == undefined && typeof data != "undefined" && data != ""){
                                $(targetDOM).find("img").attr("src","data:image/" + ext + ";base64," + data);
                            }
                            
                            if (index + 1 < renderlist.length){
                                doThumbnailSequentialLoading(startingCurrentDir, renderlist, index + 1);
                            }
                        }else{
                            //User changed page. End the sequence
                        }
                    }
                });
            }

            //Make an div not draggable
            function disableDrag(event){
                event.preventDefault();
                event.stopPropagation();
            }

            //Make fileObject draggable
            function onFileObjectDragStart(object, event){
                if ((ctrlHold) &&  $(object).hasClass("selected") == false){
                    $(object).addClass("selected");
                }else if ($(object).hasClass("selected") == false){
                    $(".fileObject.selected").removeClass("selected");
                    $(object).addClass("selected");
                }

                var fileList = [];
                $(".selected.fileObject").each(function(){
                    var filename = $(this).attr('filename');
                    var filepath = $(this).attr('filepath');
                    var sourceSystemUUID = systemUUID;
                    //Extra information is passed in due to the need for cross cluster communication in the future
                    fileList.push({
                        filename: filename,
                        filepath: filepath,
                        hostUUID: sourceSystemUUID
                    });
                });
               
                event.dataTransfer.setData("filedata", JSON.stringify(fileList));
            }

            //Bind onclicke events for fileObjects
            var lastClickedFileID = 0;
            function bindFileObjectEvents(){
                $(".fileObject").off("click").on("click",function(evt){
                    if (isMobile){
                        //There are no context menu in mobile
                        //Stop event propagation to document.click event
                        evt.stopImmediatePropagation();
                    }
                    if (renameMode && $(this).find(".renameinput").length == 0){
                        exitRenameModeWithConfirm();
                        return;
                    }else if (renameMode){
                        //Stop the click event propagating to the #fileViewer on-click exit event
                        evt.stopImmediatePropagation();
                    }

                    if (ctrlHold == true){
                        if ($(this).hasClass("selected")){
                            $(this).removeClass("selected");

                            //if there are no more selected files on the page
                            //exit multi-select mode
                            if ($(".fileObject.selected").length == 0){
                                exitMultiSelectMode();
                            }
                        }else{
                            $(this).addClass("selected");
                            if (propertiesView){
                                let filepath =  $(this).attr("filepath");
                                loadFileProperties(filepath);
                            }
                        }
                       
                        lastClickedFileID = parseInt($(this).attr("fileid"));
                    }else if (shiftHold == true){
                        //Select everything in range lastClicked to this
                        var thisFileID = $(this).attr("fileid");
                        let start = parseInt(thisFileID);
                        let end = parseInt(lastClickedFileID);
                        if (start > end){
                            start = parseInt(lastClickedFileID);
                            end = parseInt(thisFileID);
                        }
                        //Select all fileObject in range.
                        $(".fileObject").each(function(){
                            let currentItemFileID = $(this).attr('fileid');
                            currentItemFileID = currentItemFileID - 0;
                            if (currentItemFileID >= start && currentItemFileID <= end){
                                $(this).addClass("selected");
                            }
                        });
                    }else if(!ctrlHold && isMobile){
                        //If on mobile, click means open (only on not muilti selection mode)
                        evt.preventDefault();
                        evt.stopImmediatePropagation();
                        openthis(this,evt);

                        //Deselect everything if in multi-select mode
                        if (ctrlHold){
                            ctrlHold = false;
                            updateCtrlDisplay();
                        }
                        return
                    }else{
                        //Nothing is pressed. Deselect everything and add this only
                        $(".fileObject.selected").removeClass("selected");
                        $(this).addClass("selected");
                        lastClickedFileID = $(this).attr("fileID");

                        if (propertiesView){
                            loadFileProperties($(this).attr("filepath"));
                        }
                    }

                    updateSelectedObjectsCount();
                });

                //Bind right click select on items
                $(".fileObject").off("mousedown").on("mousedown",function(evt){
                    if (evt.which == 3){
                        //Right click on this file
                        if ($(this).hasClass('selected') == false){
                            $(".fileObject.selected").removeClass("selected");
                            $(this).addClass("selected");
                        }
                        
                    }
                });

                //This function calculate and offset the context menu to not go out of the window area
                function calculateContextMenuOffsets(evt){
                    var defaultLeftPost = evt.pageX + "px";
                    var defaultTopPost =evt.pageY + "px";
                    
                    if (evt.pageX > window.innerWidth / 2){
                        defaultLeftPost = evt.pageX - $("#contextmenu").width();
                        
                        if (defaultLeftPost < 0){
                            //over the left boundary
                            defaultLeftPost = 0;
                        }
                        defaultLeftPost = defaultLeftPost + "px";
                    }else{

                        if (evt.pageX + $("#contextmenu").width() > window.innerWidth){
                            //Over the right boundary
                            defaultLeftPost = window.innerWidth - $("#contextmenu").width();
                            defaultLeftPost = defaultLeftPost + "px";
                        }
                    }

                    if (evt.pageY > window.innerHeight / 2){
                        defaultTopPost = evt.pageY - $("#contextmenu").height();

                        if (defaultTopPost < 0){
                            //over the top boundary
                            defaultTopPost = 0;
                        }
                        defaultTopPost = defaultTopPost + "px"
                       
                    }else{
                        if (evt.pageY + $("#contextmenu").height() > window.innerHeight){
                            //Over the lower boundary
                            defaultTopPost =  window.innerHeight - $("#contextmenu").height();
                            defaultTopPost = defaultTopPost + "px"
                        }
                    }
                    
                    $("#contextmenu").css({
                        left: defaultLeftPost,
                        top: defaultTopPost
                    });

                }  

                //Rightclick on a file object
                $(".fileObject").off("contextmenu").on("contextmenu", function(evt){
                    evt.preventDefault();
                    if (isMobile){
                        //Firefox Mobile. Fix select with context menu not working bug
                        var selectedObject = $(evt.target);
                        
                       if ($(selectedObject).hasClass("fileObject")){
                           if (!ctrlHold){
                                $(".fileObject.selected").removeClass("selected");
                           }
                            $(selectedObject).addClass("selected");
                       }else{
                           //Uptrace 5 layers for fileObject
                           for (var i = 0; i < 5; i++){
                                if ($(selectedObject).hasClass("fileObject") == false){
                                    selectedObject = $(selectedObject).parent();
                                }else{
                                    break;
                                }
                           }

                           if (!ctrlHold){
                                $(".fileObject.selected").removeClass("selected");
                           }
                            $(selectedObject).addClass("selected");
                       }

                       if (propertiesView){
                            let filepath = $(selectedObject).attr("filepath");
                            loadFileProperties(filepath);
                        }

                        //Enable multi-select mode
                        ctrlHold = true;
                        updateCtrlDisplay();
                        return;
                    }

                    //Show all options by defaults
                    $("#contextmenu").find(".item").show();
                    $("#contextmenu").find(".vroothide").show();
                    $("#contextmenu").find(".noSelectionOnly").hide();
                    $("#contextmenu").find(".vrootonly").hide();
                    $("#contextmenu").find(".zipFileOnly").hide();

                    //Hide general menu options for single / multiple
                    if ($(".fileObject.selected").length > 1){
                        //Multiple object selected
                        $(".singleObjectOnly").addClass("disabled");
                        $(".singleObjectOnlyHide").hide();
                        console.log("Hiding");
                    }else{
                        //Single object
                        $(".singleObjectOnly").removeClass("disabled");
                        $(".singleObjectOnlyHide").show();
                    }

                    //Check if this is folder or file. Replace the suitable selections
                    if ($(this).attr("type") == "folder"){
                        //Use folder mode
                        $("#contextmenu").find(".folderonly").show();
                        $("#contextmenu").find(".fileonly").hide();
                    }else{ 
                        //Use file mode
                        $("#contextmenu").find(".folderonly").hide();
                        $("#contextmenu").find(".fileonly").show();
                    }
                    console.log($(this).attr("type"));

                    if (searchMode == true){
                        $("#contextmenu").find(".shareonly").show();
                    }else{
                        $("#contextmenu").find(".shareonly").hide();
                    }

                    $("#contextmenu").addClass("visible");
                    //Handle CSS offset of the contextmenu
                    if ($("#contextmenu").offset().top < 0){
                        $("#contextmenu").css("top","0px");
                    }else if($("#contextmenu").offset().top + $("#contextmenu").height() > window.innerHeight){
                        $("#contextmenu").css("top",window.innerHeight - $("#contextmenu").height() + "px");
                    }

                    if (isMobile){
                        $("#contextmenu").find(".mobileonly").show();
                    }else{
                        $("#contextmenu").find(".mobileonly").hide();
                    }

                    $(".fileObject.selected").each(function(){
                        if ($(this).attr("filename").split(".").pop().toLowerCase() == "zip"){
                            $(".zipFileOnly").show();
                        }
                    });

                    calculateContextMenuOffsets(evt);

                    //Disable scroll on folderView
                    //$("#folderView").addClass("fixscroll");
                });

                //Right click on empty space of the file selector
               $("#folderView").off("contextmenu").on("contextmenu", function(e){
                   if ($(e.target).attr("id") == "folderView" || $(e.target).attr("id") == "fileList" || $(e.target).attr("id") == "folderList" || $(e.target).is("table") || $(e.target).is("th")){
                       //Context menu on the empty space of the folder / file list
                        e.preventDefault();
                        $("#contextmenu").find(".item").hide();
                        $("#contextmenu").find(".noSelectionOnly").show();
                        $("#contextmenu").find(".allowNoSelection").show();
                        $("#contextmenu").find(".vroothide").show();
                        $("#contextmenu").find(".zipFileOnly").hide();

                        //Calculate the position of the context menu
                        calculateContextMenuOffsets(e);

                        //Show context menu
                        $("#contextmenu").addClass("visible");
                        //Handle CSS offset of the contextmenu
                        if ($("#contextmenu").offset().top < 0){
                            $("#contextmenu").css("top","0px");
                        }else if($("#contextmenu").offset().top + $("#contextmenu").height() > window.innerHeight){
                            $("#contextmenu").css("top",window.innerHeight - $("#contextmenu").height() + "px");
                        }

                        //Disable scroll on folderView
                        //$("#folderView").addClass("fixscroll");

                   }
               });

               //Handle right click on storage roots
               $("#storageroot").off("contextmenu").on("contextmenu", function(e){
                    if ($(e.target).is("i")){
                        e.target = e.target.parentElement;
                    }

                    $("#storageroot").find(".dir.item").each(function(){
                        if ($(this).attr("rootname") != undefined){
                            $(this).removeClass("active");
                        }
                    });

                    if ($(e.target).attr("rootname") != undefined){
                        //Correct one. Show vroot functions
                        e.preventDefault();
                        var rootname = $(e.target).attr("rootname");
                        $(e.target).addClass("active");
                        $("#contextmenu").find(".item").hide();
                        $("#contextmenu").find(".vroothide").hide();
                        $("#contextmenu").find(".vrootonly").show();

                        //Show context menu
                        calculateContextMenuOffsets(e);

                        $("#contextmenu").addClass("visible");
                        //Handle CSS offset of the contextmenu
                        if ($("#contextmenu").offset().top < 0){
                            $("#contextmenu").css("top","0px");
                        }else if($("#contextmenu").offset().top + $("#contextmenu").height() > window.innerHeight){
                            $("#contextmenu").css("top",window.innerHeight - $("#contextmenu").height() + "px");
                        }
                    }
               });

               $(document).on("click",function(evt){
                   $(".contextmenu").removeClass("visible");
                   //Record what has been clicked
                    lastClickedElement = evt.target;
                    //Enable scroll on folderView
                    //$("#folderView").removeClass("fixscroll");
               });
            }

            //Update the selected items display count
            function updateSelectedObjectsCount(){
                $("#selectInfo").text($(".fileObject").length + applocale.getString("tooltip/filecount", " items")  + " / " + $(".fileObject.selected").length + applocale.getString("tooltip/selectedcount", " selected"));
            }

            //Change the current view mode
            function changeViewMode(object){
                var targetMode = $(object).attr("mode");
                viewMode = targetMode;
                refreshList(undefined, true);
                updateViewmodeButtons();
                setPreference("file_explorer/listmode",targetMode)
            }

            //Toggle properties view
            //Setting will be save to this browser only
            function togglePropertiesView(object){
                propertiesView = !propertiesView;
                if (propertiesView){
                    $("#propertiesView").show();
                    $(object).addClass('active');
                    localStorage.setItem("file_explorer/viewProperties", "true");

                    if ($(".fileObject.selected").length >= 1){
                        //Load the file properties
                        let targetFile = getFileObjectFromFID(lastClickedFileID);
                        if (targetFile == null){
                            targetFile = $(".fileObject.selected")[0];
                        }
                        let filepath = $(targetFile).attr("filepath");
                        loadFileProperties(filepath);
                    }
                }else{
                    $("#propertiesView").hide();
                    $(object).removeClass('active');
                    localStorage.setItem("file_explorer/viewProperties", "false");
                }
            }

            function updateViewmodeButtons(){
                $(".videmode").removeClass('disabled');
                $(".videmode").each(function(){
                    if ($(this).attr("mode") == viewMode){
                        $(this).addClass("disabled");
                    }
                });
            }

            function previosPath(){
                //Remove the current directory from history
                if (viewHistory.length == 0){
                    //This is already the first page
                    return;
                }
                var previousPath = viewHistory.pop();
                listDirectory(previousPath, undefined, false);
            }

            function parentDir(){
                //If under searchmode, parentDir go back to the currentPath
                if (searchMode){
                    hideSearchBar();
                    return;
                }
                //Check if there are any parent dir for this path
                if (checkIfParentDirExists(currentPath)){
                    //There are parent path. Get it from currentPath
                    pathInfo = currentPath.split("/");
                    pathInfo.pop();
                    var parentFolderName = pathInfo.pop();
                    parentPath = pathInfo.join("/") + "/"
                    
                    //List the parentDir
                    listDirectory(parentPath, function(){
                        focusFileObject(parentFolderName);
                    });
                   
                }

            }

            //Move the page focus to the given fileobject
            //alias: Highlight file object / filename
            function focusFileObject(targetFileName){
                $(".fileObject").each(function(){
                    if ($(this).attr("filename") == targetFileName){
                        scrollToFileLocation(this);
                        $(this).addClass("selected");
                    }
                });
            }

            function scrollToFileLocation(DOMElement){
                if (DOMElement === undefined || $(DOMElement).offset() == undefined){
                    //DOM Element no longer exists
                    return;
                }
                //Trying to vertically align the directory from its parent list
                let topPos = $("#folderView").scrollTop() + $(DOMElement).offset().top - $("#folderView").height()/2 - $(DOMElement).height()/2 - 28;
                window.debug = $(DOMElement);
                $("#folderView").stop().animate({
                    scrollTop: topPos
                }, 300);
            }

            function loadListModeFromDB(callback = undefined){
                 //Get list mode from storage
                 loadPreference("file_explorer/listmode",function(data){
                    if (data != "" && data.error === undefined){
                        viewMode = data;
                        updateViewmodeButtons();
                    }

                    if (callback !== undefined){
                        callback();
                    }
                });
            }

            function rootDir(){
                //Go to the root dir of the current path
                var rootDir = currentPath.split("/").shift();
                rootDir = rootDir + "/";
                listDirectory(rootDir);
            }

            function showEditCurrentPathInput(e){
                e.preventDefault();
                e.stopImmediatePropagation();
                pathInputMode = true;
                $("#pathInputField").find("input").val(currentPath);
                $("#editPathBtn").hide();
                if (isMobile){
                    $("#mobilePathDisplay").hide();
                    $(".mobilePathDisplayWrapper").append($("#pathInputField"));
                }else{
                    //Desktop
                    $("#pathDisplayField").hide();
                }
                $("#pathInputField").show();
                $("#pathInputField").find("input").focus();
                
            }

            function handleOpenPathKeydown(e){
                if (e.key == "enter" | e.keyCode == 13){
                    //Etner pressed
                    openEnteredPath($("#pathInputField").find("button"));
                }
            }

            function openEnteredPath(object){
                var newPath = $(object).parent().find("input").val();
                //Filter out the path
                newPath = newPath.split("\\").join("/");
                listDirectory(newPath);
                hideManualOpenPathInput();

            }

            function hideManualOpenPathInput(){
                $("#pathInputField").hide();
                pathInputMode = false;
                if (isMobile){
                    $("#mobilePathDisplay").show();
                }else{
                    $("#pathDisplayField").show();
                }
                
                //Restore the edit btn
                $("#editPathBtn").show();
            }

            $("#folderView").on("click", function(){
                if (pathInputMode){
                    hideManualOpenPathInput();
                }

                if (renameMode && $(".renameinput").length > 0){
                    exitRenameModeWithConfirm();
                    return;
                }
            })

            function checkIfParentDirExists(path){
                if (path.includes("/")){
                    pathInfo = path.split("/");
                    if (pathInfo[1] == ""){
                        return false;
                    }else{
                        return true;
                    }
                }else{
                    return false;
                }
            }

            function getDirHash(callback){
                $.ajax({
                    url: "../../system/file_system/listDirHash",
                    data: {dir: currentPath},
                    success: function(data){
                        if (data.error !== undefined){
                            if (data.error == "Invalid dir given"){
                                //Storage has been unmounted. Back to parent
                                var pdir = currentPath.split("/");
                                pdir.pop();pdir.pop();
                                pdir = pdir.join("/");
                                currentPath = pdir;
                                listDirectory(currentPath, function(){
                                    window.location.reload();
                                });
                                return;
                            }else if (data.error == "Unable to resolve target directory"){
                                //Resolve failed. Back to user:/
                                var pdir = currentPath.split("/");
                                pdir = pdir.shift() + "/";
                                listDirectory(pdir, function(){
                                    window.location.reload();
                                });
                            }
                        }
                        callback(data);
                    }
                })
            }

            function openHomeDir(){
                listDirectory("user:/", function(){
                    hideManualOpenPathInput();
                    hideSearchBar();
                })
            }

            //=================================== FILE OPERATIONS ========================

            function refreshList(callback = undefined, keepSelectedItems = false){
                if (searchMode == true){
                    //Refresh the search result
                    if ($("#searchInput").val().length >  0){
                        handleSearch();
                    }
                    return;
                }

                shiftHold = false;
                if (!isMobile){
                    //Desktop mode only, to prevent focus out when ctrl Up
                    ctrlHold = false;
                }

                let filenameBackups = [];
                if (keepSelectedItems){
                    //Backup all the selected filenames
                    $(".fileObject.selected").each(function(){
                        filenameBackups.push($(this).attr("filename"));
                    });
                }
                console.log(filenameBackups);
                updateCtrlDisplay();
                listDirectory(currentPath, function(){
                    if (keepSelectedItems){
                        $(".fileObject").each(function(){
                            if (filenameBackups.includes($(this).attr("filename"))){
                                $(this).addClass("selected");
                            }
                        });
                    }
                    if (callback != undefined){
                        callback();
                    }
                });
            }

           function zipFile(){
                $(".popup").fadeOut('fast');
                var zippingFiles = [];
                $(".fileObject.selected").each(function(){
                    var filepath = $(this).attr("filepath");
                    zippingFiles.push(filepath);
                });

                console.log(zippingFiles);

                //Request to create a zip file, named with the parent dir name
                var oprConfig = {
                    opr: "zip",
                    src: zippingFiles,
                    dest: currentPath,
                    overwriteMode: "overwrite",
                    callbackWindowID: ao_module_windowID,
                    callbackFunction: `callRefresh("${currentPath}")`
                }
                var configHash = encodeURIComponent(JSON.stringify(oprConfig));
                var title = applocale.getString("opr/zip/zipping","Zipping ") +  zippingFiles.length;
                if (fileList.length > 1){
                    title += applocale.getString("opr/zip/files", " files");
                }else{
                    title += applocale.getString("opr/zip/file"," file");
                }

                if (!ao_module_virtualDesktop){
                    window.open("file_operation.html#" + configHash);
                }else{
                    parent.newFloatWindow({
                        url: "SystemAO/file_system/file_operation.html#" + configHash,
                        width: 400,
                        height: 220,
                        appicon: "SystemAO/file_system/img/selector.png",
                        title: title
                    });
                }

                
           }

           function unzipHere(){
                $(".popup").fadeOut('fast');

                //Get a list of zip files selected
                var unzippingFiles = [];
                $(".fileObject.selected").each(function(){
                    var filepath = $(this).attr("filepath");
                    if ((filepath.split(".").pop()).toLowerCase() == "zip"){
                        unzippingFiles.push(filepath);
                    }
                });

                if(unzippingFiles.length == 0){
                    msgbox("red remove", applocale.getString("opr/zip/nozipfile", "No zip file selected"));
                    return;
                }

                //Start unzip progress
                console.log(unzippingFiles);

                //Unzip and open them to tmp:/
                var oprConfig = {
                    opr: "unzip",
                    src: unzippingFiles,
                    dest: currentPath,
                    overwriteMode: "overwrite",
                    callbackWindowID: ao_module_windowID,
                    callbackFunction: `callRefresh("${currentPath}")`
                }

                //Render the dialog title name
                var configHash = encodeURIComponent(JSON.stringify(oprConfig));
                var title = applocale.getString("opr/zip/unzipping","Unzipping ") + unzippingFiles.length;
                if (unzippingFiles.length > 1){
                    title += applocale.getString("opr/zip/files", " files");
                }else{
                    title += applocale.getString("opr/zip/file"," file");
                }

            
                if (!ao_module_virtualDesktop){
                    window.open("file_operation.html#" + configHash);
                }else{
                    parent.newFloatWindow({
                        url: "SystemAO/file_system/file_operation.html#" + configHash,
                        width: 400,
                        height: 220,
                        appicon: "SystemAO/file_system/img/selector.png",
                        title: title,
                    });
                }

           }

            let renameFileObjects = [];
            function rename(){
                hideAllPopupWindows();
                renameFileObjects = [];
                var filenames = [];
                $(".fileObject.selected").each(function(){
                    var fileObjectType = $(this).attr("type");
                    let fileObject = {
                        filename: $(this).attr('filename'),
                        filepath: $(this).attr("filepath"),
                        filetype: fileObjectType
                    }
                    renameFileObjects.push(JSON.parse(JSON.stringify(fileObject)));
                    filenames.push($(this).attr('filename'));
                });
                var oldname = "unknown file.txt";
                if (renameFileObjects.length == 0){
                    return;
                }else if (renameFileObjects.length > 0){
                    $("#renameBox").find(".multifileWarning").hide();
                    oldname = filenames[0];
                }   

                //Override with rename input box
                renameMode = true;

                if (isMobile){
                    //Mobile rename using sidebar dialog
                    $("#renameBox").find(".orgfn").val(oldname);
                    $("#renameBox").find(".newfn").val(oldname);
                    showPopupWrapper();
                    $("#renameBox").transition('slide left in');
                }else{
                    //Desktop rename
                    let rootObject = $($(".fileObject.selected")[0]);
                    $(rootObject).addClass("renaming");
                    let targetDOM = $(rootObject).find(".filename");
                    rootObject.attr("draggable", "false");
                    if (viewMode == "list"){
                        $(targetDOM).html(`<div class="renameinput" oldname="${encodeURIComponent(oldname)}" onkeydown="handleInputConfirmRename(this, event);" style="width: calc(100% - 5em); display: inline-block;">
                            <input type="text" value="${oldname}">
                        </div>`);
                        $(rootObject).find(".sharebtn").remove();
                    }else if (viewMode == "grid"){
                        $(targetDOM).html(`<div class="renameinput" oldname="${encodeURIComponent(oldname)}" onkeydown="handleInputConfirmRename(this, event);" style="width: 100%; display: inline-block;">
                            <input type="text" value="${oldname}">
                        </div>`);
                    }else if (viewMode == "details"){
                        $(targetDOM).html(`<div class="renameinput" oldname="${encodeURIComponent(oldname)}" onkeydown="handleInputConfirmRename(this, event);" style="width: calc(100% - 5em); display: inline-block;">
                            <input type="text" value="${oldname}">
                        </div>`);
                    }
                    
                    let targetInputField = $(".renameinput").find("input")[0];
                    $(targetInputField).focus();
                    targetInputField.selectionStart = 0;
                    targetInputField.selectionEnd = targetInputField.value.lastIndexOf(".");
                }
            }

            //Exit rename mode with current name in filename as new filename
            //Activate from clicking elsewhere
            function exitRenameModeWithConfirm(applyChange = true){
                let renamingObject = $($(".renameinput")[0]);
                $(".fileObject.renaming").removeClass("renaming");
                let newname = renamingObject.find("input").val();
                let oldname = renamingObject.attr("oldname");
                oldname = decodeURIComponent(oldname);
                if (oldname == newname || !applyChange){
                    //Cancel Rename, in cases where old name = new name or applyChange set to false
                    let filenameField = $(renamingObject).parent();
                    $(filenameField).html(oldname);
                    renameMode = false;
                    return;
                }
                confirmRename(oldname, newname);
            }

            //Handle enter press on rename input box
            function handleInputConfirmRename(object, evt){
                let filenameForbiddenCharKey = [
                    '/',
                    '<',
                    '>',
                    ':',
                    '"',
                    '\\',
                    '*'
                ];
                if (evt.keyCode == 13){
                    evt.preventDefault();
                    evt.stopImmediatePropagation();
                    let oldname = $(object).attr("oldname").trim();
                    let newname = $(object).find("input").val().trim();
                    $(".fileObject.selected.renaming").removeClass("renaming");
                    if (oldname == newname){
                        //Cancel Rename
                        let filenameField = $(object).parent();
                        $(filenameField).html(oldname);
                        renameMode = false;
                        return;
                    }
                    confirmRename(oldname, newname);
                }else if (evt.keyCode == 27){
                    //ESC key, restore to origin
                    //Exit rename mode but not apply change
                    exitRenameModeWithConfirm(false);
                }else if (filenameForbiddenCharKey.includes(evt.key)){
                    //Show now allow popup
                    evt.preventDefault();
                }
            }
            

            function confirmRename(oldName=undefined, newName=undefined){
                renameMode = false;
                if (oldName == undefined){
                    oldName = $("#renameBox").find(".orgfn").val().trim();
                }

                if (newName == undefined){
                    newName = $("#renameBox").find(".newfn").val().trim();
                }

                if (newName == oldName){
                    msgbox("red remove",applocale.getString("message/newFilenameIdentical", "New filename is identical to the original filename."));
                    hideAllPopupWindows();
                    return;
                }
                var newNameWithoutExt = newName;
                var newnameExt = "";
                if (newName.includes(".")){
                    tmp = newName.split(".");
                    newnameExt = tmp.pop();
                    newNameWithoutExt = tmp.join(".");
                }

                var counter = 0;
                var srclist = [];
                var newnamelist = [];

                for (var i =0; i < renameFileObjects.length; i++){
                    var thisFilepath = renameFileObjects[i].filepath;
                    var thisFiletype = renameFileObjects[i].filetype;
                    var thisFilename = renameFileObjects[i].filename;
                    
                    var newFilename = newName;
                    if ( i > 0){
                        if (thisFiletype == "file"){
                            var thisFileExt = thisFilename.split(".").pop();
                            newFilename = newNameWithoutExt + "(" + i + ")." + thisFileExt;
                        }else if (thisFiletype == "folder"){
                            newFilename = newNameWithoutExt + "(" + i + ")";
                        }
                    }
                    srclist.push(thisFilepath);
                    newnamelist.push(newFilename);
                   
                }
                console.log(srclist, newnamelist);
                //Send the request to serverside
                requestCSRFToken(function(token){
                    $.ajax({
                        url: "../../system/file_system/fileOpr",
                        method: "POST",
                        data: {opr: "rename", src: JSON.stringify(srclist), new: JSON.stringify(newnamelist), csrft: token},
                        success: function(data){
                            if (data.error !== undefined){
                                msgbox("red remove",applocale.getString("message/" + data.error, data.error));
                            }else{
                                refreshList(function(){
                                    focusFileObject(newName);
                                });
                                msgbox("checkmark",applocale.getString("message/rename/success", "Rename suceed"));
                            }
                            hideAllPopupWindows();
                        },
                        error: function(){
                            hideAllPopupWindows();
                        }
                    });
                    renameFileObjects = [];
                });
            
            }

            function changeOverwriteRule(mode, doPasteAgain=false){
                switch (mode){
                    case 0:
                        overwriteMode = "overwrite";
                        break;
                    case 1:
                        overwriteMode = "skip";
                        break;
                    case 2:
                        overwriteMode = "keep";
                        break;
                    default:
                    overwriteMode = "keep";
                }

                if (doPasteAgain){
                    //Initiate paste without checking and close the overwritemode selector
                    paste(undefined, true);
                }
            }


            function copy(){
                cutMode = false;
                clipboard = [];
                if ($(".fileObject.selected").length == 0){
                    return;
                }

                $(".fileObject.selected").each(function(){
                    var thisFilepath = $(this).attr("filepath");
                    clipboard.push(thisFilepath);
                });
                if (useLocalstorage){
                    localStorage.setItem("ao/file_system/clipboard",JSON.stringify(clipboard));
                    localStorage.setItem("ao/file_system/cutmode","false");
                }
                msgbox("copy",clipboard.length + applocale.getString("message/copy/success", " objects copied."))
            }

            function cut(){
                cutMode = true;
                clipboard = [];
                if ($(".fileObject.selected").length == 0){
                    return;
                }
                $(".fileObject.selected").each(function(){
                    var thisFilepath = $(this).attr("filepath");
                    clipboard.push(thisFilepath);
                });
                if (useLocalstorage){
                    localStorage.setItem("ao/file_system/clipboard",JSON.stringify(clipboard));
                    localStorage.setItem("ao/file_system/cutmode","true");
                }
                msgbox("cut",clipboard.length + applocale.getString("message/move/success", " objects ready to be moved."))
            }

            function paste(redirectPasteTarget="", nocheck=false){
                let thisOprCutMode = cutMode;
                let fileList = clipboard;
                let targetDir = currentPath;
                if (redirectPasteTarget != ""){
                    //Allow redirection of paste target if necessary
                    targetDir = redirectPasteTarget;
                }
                if (useLocalstorage){
                    //There are localStorage. Always use localStorage if exists.
                    var crossFrameClipboard = localStorage.getItem("ao/file_system/clipboard");
                    var useCutMode = localStorage.getItem("ao/file_system/cutmode");
                    if (crossFrameClipboard !== "" && crossFrameClipboard !== undefined && crossFrameClipboard !== null){
                        fileList = JSON.parse(crossFrameClipboard);
                    }
                    if (useCutMode !== "" && useCutMode !== undefined && useCutMode !== null){
                        thisOprCutMode = (useCutMode == "true");
                    }
                }
                if (fileList.length == 0){
                    //There are nothing to paste
                    msgbox("question",applocale.getString("message/paste/nothing", "There are nothing to paste."))
                    return;
                }
                //console.log(fileList,JSON.stringify(fileList));
                if (thisOprCutMode == true){
                    //Cut and paste
                    $.ajax({
                        type: 'POST',
                        url: `../../system/file_system/validateFileOpr`,
                        data: {src: JSON.stringify(fileList), dest: targetDir},
                        success: function(data){
                           if (!nocheck && data.length > 0){
                               //There are problem with the copy target. Pop up overwrite rule selector
                                showDuplicateHandler(data);
                           }else{
                               //OK!
                               //Clear clipboard settings
                               localStorage.setItem("ao/file_system/clipboard", "");
                               clipboard = "";

                               //Stsart operations
                               if (!ao_module_virtualDesktop){
                                   //Not under desktop mode. Use direct copy API
                                   requestCSRFToken(function(token){
                                        $.ajax({
                                            type: 'POST',
                                            url: `../../system/file_system/fileOpr`,
                                            data: {opr: "move" ,src: JSON.stringify(fileList), dest: targetDir,existsresp: overwriteMode, csrft: token},
                                            success: function(data){
                                                if (data.error !== undefined){
                                                    msgbox("red remove",applocale.getString("message/" + data.error, data.error));
                                                }else{
                                                    //OK
                                                    msgbox("checkmark",fileList.length + applocale.getString("message/move/success", " objects moved."))
                                                    refreshList();
                                                }
                                                hideAllPopupWindows();
                                            }
                                        });
                                   });
                                   
                               }else{
                                    //Pass the request to operation handler
                                    var oprConfig = {
                                        opr: "move",
                                        src: fileList,
                                        dest: targetDir,
                                        overwriteMode: overwriteMode,
                                        callbackWindowID: ao_module_windowID,
                                        callbackFunction: `callRefresh("${targetDir}")`
                                    }
                                    var configHash = encodeURIComponent(JSON.stringify(oprConfig));
                                    var title = "Moving " + fileList.length;
                                    if (fileList.length > 1){
                                        title += " files";
                                    }else{
                                        title += " file";
                                    }
                                    parent.newFloatWindow({
                                        url: "SystemAO/file_system/file_operation.html#" + configHash,
                                        width: 400,
                                        height: 220,
                                        appicon: "SystemAO/file_system/img/selector.png",
                                        title: title
                                    });
                                    hideAllPopupWindows();
                               }
                           }
                        }
                    });
                }else{
                    //Copy and paste
                    //Check if the file list is OK for continue without the need for overwrite
                    $.ajax({
                        type: 'POST',
                        url: `../../system/file_system/validateFileOpr`,
                        data: {src: JSON.stringify(fileList), dest: targetDir},
                        success: function(data){
                           if (!nocheck && data.length > 0){
                               //There are problem with the copy target. Pop up overwrite rule selector
                                showDuplicateHandler(data);
                           }else{
                               //OK!
                               if (!ao_module_virtualDesktop){
                                    requestCSRFToken(function(token){
                                        $.ajax({
                                            type: 'POST',
                                            url: `../../system/file_system/fileOpr`,
                                            data: {opr: "copy" ,src: JSON.stringify(fileList), dest: targetDir,existsresp: overwriteMode, csrft: token},
                                            success: function(data){
                                                if (data.error !== undefined){
                                                    msgbox("red remove",applocale.getString("message/" + data.error,data.error));
                                                }else{
                                                    //OK
                                                    msgbox("checkmark",fileList.length + applocale.getString("message/copy/success", " objects copied."))
                                                    refreshList();
                                                }
                                                hideAllPopupWindows();
                                            }
                                        });
                                    });
                                    
                               }else{
                                    //Pass the request to operation handler
                                     var oprConfig = {
                                        opr: "copy",
                                        src: fileList,
                                        dest: targetDir,
                                        overwriteMode: overwriteMode,
                                        callbackWindowID: ao_module_windowID,
                                        callbackFunction: `callRefresh("${targetDir}")`
                                    }
                                    var configHash = encodeURIComponent(JSON.stringify(oprConfig));
                                    var title = "Copying " + fileList.length;
                                    if (fileList.length > 1){
                                        title += " files";
                                    }else{
                                        title += " file";
                                    }
                                    parent.newFloatWindow({
                                        url: "SystemAO/file_system/file_operation.html#" + configHash,
                                        width: 400,
                                        height: 220,
                                        appicon: "SystemAO/file_system/img/selector.png",
                                        title: title
                                    });
                                    hideAllPopupWindows();
                               }
                               
                           }
                        }
                    });
                }
            }

            //Callback function for file operation display
            window.callRefresh = function(targetdir){
                console.log(currentPath, targetdir);
                if (currentPath == targetdir){
                    refreshList();
                }
            }

            //This action may duplicate files. Show handler
            function showDuplicateHandler(duplicateFileList){
                $(".popup").fadeOut(100);
                var duplicatedFileCounts = duplicateFileList.length;
                showPopupWrapper();
                $("#overwriteModeSelection").transition("slide left in");
                $("#overwriteModeSelection").find(".owm-fc").text(duplicatedFileCounts);
                var srcpath = duplicateFileList[0];
                srcpath = srcpath.split("/");
                srcpath.pop();
                srcpath = srcpath.join("/");
                $("#overwriteModeSelection").find(".owm-srcdir").text(srcpath);
                $("#overwriteModeSelection").find(".owm-destdir").text(currentPath);
            }

            //Force delete. Use normal delete fucntion if you want to move things to recycle bin instead.
            let forceDeleteList = [];
            function forceDelete(confirmed=false){
                if (!confirmed){
                    //Show confirm box
                    let deletePendingList = [];
                    var listObject = $("#forceDeleteConfirmBox").find(".deleteFilelist")[0];
                    $(listObject).html("");
                    $(".selected.fileObject").each(function(data){
                        var thispath = $(this).attr("filepath");
                        var thisfilename = $(this).attr("filename");
                        var ext = thisfilename.split(".").pop();
                        var icon = ao_module_utils.getIconFromExt(ext);
                        deletePendingList.push(thispath);
                        $(listObject).append(`<div class="item" ><span style="display:inline-block;">${thisfilename}</span></div>`);
                    });
                    showPopupWrapper();
                    $("#forceDeleteConfirmBox").transition("slide left in");
                    forceDeleteList = deletePendingList;
                }else{
                    //Start force delete function
                    let fdlistLength = forceDeleteList.length;
                    requestCSRFToken(function(token){
                        $.ajax({
                            url: "../../system/file_system/fileOpr",
                            method:"POST",
                            data: {opr: "delete", src: JSON.stringify(forceDeleteList), csrft: token},
                            success: function(data){
                                if (data.error !== undefined){
                                    msgbox("red remove",applocale.getString("message/" + data.error,data.error));
                                }else{
                                    refreshList();
                                    msgbox("checkmark",fdlistLength + applocale.getString("message/remove/success", " objects removed."))
                                }
                            }
                        });
                        //Finishing up delete sequence
                        forceDeleteList = [];
                        hideAllPopupWindows();
                    });
                    
                }
            }

            let deleteFileList = [];
            function deleteFile(confirmed = false){
                if (!confirmed){
                    //Show the confirm dialog
                    $("#deleteConfirmBox").find(".deleteFilelist").html("");
                    $(".fileObject.selected").each(function(data){
                        var thisfilename = $(this).attr('filename');
                        var thisFilepath = $(this).attr('filepath');
                        deleteFileList.push(thisFilepath);
                        $("#deleteConfirmBox").find(".deleteFilelist").append(`<div class="item" ><span style="display:inline-block;">${thisfilename}</span></div>`);
                    });
                    if (deleteFileList.length == 0){
                        //No files selected
                        return;
                    }else{
                        //File selected. Continue to delete
                        showPopupWrapper();
                        $("#deleteConfirmBox").transition("slide left in");
                    }
                }else{
                    //Continue to delete files
                    let fdlistLength = deleteFileList.length;
                    requestCSRFToken(function(token){
                        $.ajax({
                            url: "../../system/file_system/fileOpr",
                            method:"POST",
                            data: {opr: "recycle", src: JSON.stringify(deleteFileList), csrft: token},
                            success: function(data){
                                if (data.error !== undefined){
                                    msgbox("red remove",applocale.getString("message/" + data.error,data.error));
                                }else{
                                    refreshList();
                                    msgbox("checkmark",fdlistLength + applocale.getString("message/recycle/success", " objects moved to trash bin."))
                                }

                                if (currentPath == "user:/"){
                                    //Reload the User root folder list
                                    initRootDirs();
                                }
                            }
                        });
                        console.log(deleteFileList);
                        deleteFileList = [];
                        hideAllPopupWindows();
                    });
                   
                }
            }

            function cancelDelete(){
                deleteFileList=[];
                hideAllPopupWindows();
            }            

            function cancelForceDelete(){
                forceDeleteList = [];
                hideAllPopupWindows();
            }

            function createDesktopShortcut(){
                let folders = [];
                let filenames = [];
                if ($(".fileObject.selected").length == 0){
                    return;
                }
                $(".fileObject.selected").each(function(){
                    var thisFilepath = $(this).attr("filepath");
                    var thisFilename = $(this).attr("filename");
                    if($(this).attr("type") == "folder"){
                        folders.push(thisFilepath);
                        filenames.push(thisFilename);
                    }
                });

                let targetFolder = folders[0];
                let targetFilename = filenames[0];
                $.ajax({
                    url: "../../system/desktop/createShortcut",
                    method: "POST",
                    data: {
                        stype: "folder",
                        stext: targetFilename,
                        spath: targetFolder,
                        sicon: "img/system/folder-shortcut.png",
                        sdest: "user:/Desktop/",
                    },
                    success: function(data){
                        if (data.error !== undefined){
                            console.log("[File Manager] Shortcut creation failed: ", data.error)
                            msgbox("red remove",applocale.getString("opr/shortcut/error", "Shortcut creation failed. See console for more information.") , 3000);
                        }else{
                            msgbox("checkmark", applocale.getString("opr/shortcut/ok", "Shortcut created successfully"),  3000);
                            if (ao_module_virtualDesktop){
                                parent.refresh();
                            }
                        }
                    }
                })
            }

            function upload(){
                var input = document.createElement('input');
                input.type = 'file';
                input.multiple = true;
                input.onchange = e => { 
                    var files = e.target.files; 
                    msgbox("upload",applocale.getString("message/upload/started", "Upload Started"));
                    for (var i = 0; i < files.length; i++){
                        uploadFile(files[i]);
                    }
                }
                input.click();
            }

            function updatePathDisplay(path){
                var pathInfo = path.split("/");
                var vdID = pathInfo[0];
                //As path always end with /, pop the empty pathinfo from array
                pathInfo.pop();
                var l = pathInfo.length;
                //Append the starting vdir
                $(".pathDisplay").html("");
                $(".pathDisplay").append(`<div class="section selectable" onclick="event.stopImmediatePropagation(); rootDir();"><i class="folder icon"></i> ${vdID}</div>`);
                $(".pathDisplay").append(`<div class="divider">/</div>`);
                //console.log(pathInfo);
                let domPathChunks = [];
                let thisPath = vdID + "/";
                for(var i = 1; i < pathInfo.length; i++){
                    let thisname = pathInfo[i];
                    thisPath += thisname + "/";
                    let pathHighlight = "";
                    if (i < pathInfo.length - 1){
                        pathHighlight = pathInfo[i + 1];
                    }
                    domPathChunks.push(`<div class="section selectable" onclick="event.stopImmediatePropagation(); listDirectoryAndHighlight('${thisPath}', '${pathHighlight}');">${shortenLongFoldername(thisname, 20)}</div>`);
                }

                let fullpath = domPathChunks.join(`<div class="divider">/</div>`);
                let targetDisplayDOM = $("#pathDisplayField");
                if (isMobile){
                    targetDisplayDOM = $("#mobilePathDisplay");
                }
                $(targetDisplayDOM).append(`<div id="pre-render" class="measure">${fullpath}</div>`);
                let pathWidth = $("#pre-render").width();
                let pathFieldWidth = $(targetDisplayDOM).width();
                let counter = 0;

                //Check for a combination that just fit the path bar
                while(pathWidth > (pathFieldWidth - 80) && counter < l-2){
                    //Drop the first segment, only keep last one in extreme cases
                    console.log(counter, l);
                    domPathChunks.shift();
                    fullpath = `<div class="section">...</div><div class="divider">/</div>` + domPathChunks.join(`<div class="divider">/</div>`);
                    $("#pre-render").html(fullpath);
                    pathWidth = $("#pre-render").width();
                    counter++;
                }
                //Render the final address into a visiable field
                $("#pre-render").remove();
                $(targetDisplayDOM).append(fullpath);

                //Update the manual input field as well
                $("#pathInputField").find("input").val(path);
            }

            function shortenLongFoldername(name, maxchar = 20){
                var resultname = name;
                if (name.length > maxchar){
                    //Shorten it
                    var offset = parseInt((maxchar - 2) / 2);
                    resultname = name.substr(0, offset) + "..." + name.substr(name.length - offset)
                }

                return resultname
            }

            function getExtFromPath(path){
                if (path.includes(".") == false){
                    return "";
                }
                return path.split(".").pop();
            }

            function getFileObjectFromFID(fid){
                var targetFileObject = null;
                $(".fileObject").each(function(){
                    if ($(this).attr("fileid") == fid){
                        targetFileObject = $(this);
                    }
                });
                return targetFileObject;
            }

            function openViaButton(){
                let fileOpenList = [];
                let foldersToBeOpened=[];
                $(".fileObject.selected").each(function(){
                    let type = $(this).attr("type");
                    let filepath = $(this).attr("filepath");
                    if (type == "file"){
                        fileOpenList.push(filepath);
                    }else if (type == "folder"){
                        foldersToBeOpened.push(filepath);
                    }
                });
                //Open files
                openPathWithDefaultOpener(fileOpenList);

                //Open folders
                openFolderInNewWindow(foldersToBeOpened);
            }

            function openthis(object,evt=null, isDoubleClick=false){
                if (evt !== null){
                    evt.preventDefault();
                }

                if (isDoubleClick && isMobile && ctrlHold){
                    //User is clicking too fast or touch screen is too sensitive! ignore this double click
                    return;
                }

                if (renameMode && $(object).find(".renameinput").length > 0){
                    //This object is currently under rename. Ignore input
                    return;
                }else if (renameMode){
                    //Opening another stuffs. Exit renameMode
                    exitRenameModeWithConfirm();
                }
                
                var objType = $(object).attr("type");
                if ( objType == "file"){
                    //Open this file. Generate the access path from filepath
                    var filepath = $(object).attr("filepath");
                    //Only one path to be opened. Pass in as a single object array
                    openPathWithDefaultOpener([filepath]);
                }else if (objType == "folder"){
                    //Open this folder
                    var folderPath = $(object).attr('filepath');
                    listDirectory(folderPath, function(){
                        //Scroll to top of the list
                        $("#folderView").stop().finish().animate({
                            scrollTop: 0
                        }, 300);

                        if ($(object).hasClass('dir') && isMobile){
                            toggleSidebar();
                        }
                    });
                }else if (objType == "shortcut"){
                    //Load the shortcut information
                    
                    getShortcutInfo($(object).attr('filepath'), function(shortcutInfo){
                        /*
                            Shortcut Info format
                            0: Shortcut type
                            1: Shortcut Name
                            2: Shortcut target 
                            3: Shortcut icon image
                        */
                        if (shortcutInfo[0] == "module"){
                            //This is a module
                            if (ao_module_virtualDesktop){
                                //Open Module with VDI API
                                parent.openModule(shortcutInfo[2]);
                            }else{
                                //Open module in new tab
                                $.get("../../system/modules/getLaunchPara?module=" + shortcutInfo[2], function(data) {
                                    window.open("../../" + data.StartDir);
                                });
                            }
                        }else if (shortcutInfo[0] == "folder"){
                            //This is a folder
                            listDirectory(shortcutInfo[2]);
                        }else if (shortcutInfo[0] == "url"){
                            //This is a url shortcut
                            //Update 2020_02-03: Open with floatWindow instead
                            parent.newFloatWindow({
                                url: shortcutInfo[2],
                                appicon: shortcutInfo[3],
                                title: shortcutInfo[1],
                                parent: shortcutInfo[2]
                            })

                            //window.open(shortcutInfo[2]);
                        }
                        console.log(shortcutInfo);
                    });
                    
                    
                }

                //Check if this opened in sidebar and in mobile mode. Close sidebar if yes
               
            }

            /*
                Shortcut Info format
                0: Shortcut type
                1: Shortcut Name
                2: Shortcut target 
                3: Shortcut icon image
            */
            function getShortcutInfo(filepath, callback){
                $.get("../../media?file=" + filepath, function(data){
                    //This return the shortcut information. Split it and see what shortcut is this
                    data = data.split("\r\n").join("\n");
                    var shortcutInfo = data.trim().split("\n");
                    callback(shortcutInfo);
                });
            }

            //Download the selected files.
            function downloadFile(){
                var fileList = [];
                if ($(".fileObject.selected").length == 1 && $(".fileObject.selected").attr("type") == "file"){
                    //One file. Download directly.
                    var downloadURL = "../../media/download?file=" + encodeURIComponent($(".fileObject.selected").attr("filepath"));
                    var filename = $(".fileObject.selected").attr("filename");
                    generateDownloadFromURL(downloadURL,escape(filename));
                }else if ($(".fileObject.selected").length > 1 || ($(".fileObject.selected").length == 1 && $(".fileObject.selected").attr("type") == "folder")){
                    //Do zip and download for multiple files
                    $(".fileObject.selected").each(function(){
                        fileList.push($(this).attr("filepath"));
                    });
                    console.log("Zipping: ", fileList);

                    //Add a display for file compression
                    var fileCount = $(".fileObject.selected").length;
                    
                    var displayString = applocale.getString("opr/zip/zipping", "Zipping ") + fileCount + applocale.getString("opr/zip/files", " files");
                    if (fileCount == 1){
                        //Use the filename as task name
                        displayString = applocale.getString("opr/zip/zipping", "Zipping ") + $(".fileObject.selected").attr("filename");
                    }
         
                    var taskUUID = appendUploadFileItem(displayString, -1);
                    $("#uploadTab").show();

                    //Set the progress bar to intermediate mode
                    let targetTaskDisplayObject =  getUploadTaskByID(taskUUID);
                    targetTaskDisplayObject.find(".progress").addClass("preparing");

                    //Zip the file or folder
                    $.ajax({
                        url: "../../system/file_system/zipHandler",
                        data: {opr: "tmpzip", src: JSON.stringify(fileList), dest: ""},
                        method: "POST",
                        success: function(data){
                            if (data.error !== undefined){
                                //Error
                                targetTaskDisplayObject.find(".progress").removeClass("preparing").removeClass("primary").addClass("error");
                                msgbox("red remove",applocale.getString("message/" + data.error,data.error));
                            }else{
                                //Zip completed.
                                targetTaskDisplayObject.find(".progress").removeClass("preparing").removeClass("primary").addClass("positive");

                                //Open the zip file
                                window.open("../../media/download?file=" + data);
                            }

                           
                            targetTaskDisplayObject.find(".bar").css("width", "100%");

                            //Hide the taskbar after 5 secs
                            setTimeout(function(){
                                //Fade out this task
                                $(targetTaskDisplayObject).fadeOut('fast',
                                    function(){
                                        $(this).remove();
                                        if ($(".uploadTask").length == 0){
                                            $("#uploadTab").hide();
                                        }
                                    }
                                );
                               
                            }, 3000);
                            
                        }, 
                        error: function(){
                            targetTaskDisplayObject.find(".progress").removeClass("preparing").removeClass("primary").addClass("error");
                            targetTaskDisplayObject.find(".bar").css("width", "100%");
                            msgbox("red remove",applocale.getString("message/zip/fail", "Zipping failed due to unknown reason"));

                            setTimeout(function(){
                                if ($(".uploadTask").length == 0){
                                    $("#uploadTab").hide();
                                }
                            }, 3000);
                        }
                    });
                    
                }else{
                    msgbox("red remove",applocale.getString("message/No file selected", "No file selected"));
                    //alert("No file selected!")
                }
                
            }

            //Create a new file
            function newfile(){
                $(".popup:visible ").transition('slide left out');
                showPopupWrapper();
                $("#newFile").transition('slide left in');
                $("#newFile").find(".duplicateWarning").hide();
                $("#createNewFileName").parent().removeClass("error");
                //Update the newfile list
                $("#newFile").find(".newfilelist").html("");
                requestCSRFToken(function(token){
                    $.ajax({
                        url: "../../system/file_system/newItem",
                        data: {csrft: token},
                        success: function(data){
                            if (data.error !== undefined){
                                return;
                            }
                            for (var i =0; i < data.length; i++){
                                var desc = data[i].Desc;
                                var ext = data[i].Ext;
                                var icon = ao_module_utils.getIconFromExt(ext);
                                $("#newFile").find(".newfilelist").append(`<div class="item newFileFormat" ext="${ext}"><i class="${icon} icon" style="margin-right:12px;"></i> ${desc}</div>`);
                            }
                            //Initialize the new file as txt
                            var filename = "newfile";
                            var finalFilename = filename; 
                            var i = 0;
                            while (currentFilelist.includes(finalFilename)){
                                finalFilename = finalFilename + "(" + i + ")";
                                i++;
                            }  
                            $("#createNewFileName").val(finalFilename + ".txt");

                            //Hook events for on click
                            $(".newFileFormat").off("click").on("click",function(data){
                                $(".newFileFormat").removeClass("selected");
                                $(this).addClass("selected");

                                //Parse the newfilename
                                var selectedExt = $(this).attr("ext");
                                var filename = "newfile";
                                var finalFilename = filename; 
                                var i = 0;
                                while (currentFilelist.includes(finalFilename)){
                                    finalFilename = finalFilename + "(" + i + ")";
                                    i++;
                                }  
                                $("#createNewFileName").val(filename + "." + selectedExt);
                            });
                        }
                    });
                });
            }

            function filePermission(){
                //Open file permission window
                if ($(".fileObject.selected").length > 0){
                    //Build the filelist
                    var fileList = [];
                    $(".fileObject.selected").each(function(){
                        var filepath = $(this).attr("filepath");
                        fileList.push(filepath);
                    });

                    var hashPassthrough = encodeURIComponent(JSON.stringify(fileList));

                    ao_module_newfw({
                        url: "SystemAO/file_system/file_permission.html#" + hashPassthrough,
                        width: 340,
                        height: 480,
                        appicon: "SystemAO/file_system/img/properties.png",
                        title: "File Permissions",
                    })
                }
            }

            function newFolder(confirmed = false){
                if (confirmed == false){
                    //Launch the dialog for newFolder
                    hideAllPopupWindows();
                    $("#createNewFolder").val("");
                    $("#createNewFolder").parent().removeClass("error").removeClass("success");
                    $("#newFolder").find(".duplicateWarning").hide();
                    showPopupWrapper();
                    $("#newFolder").transition("slide left in");
                }else{
                    //Create new folder
                    var newFoldername = $("#createNewFolder").val().trim();
                    if (newFoldername == ""){
                        $("#createNewFolder").parent().addClass("error");
                        return;
                    }

                    //Check for invalid characters
                    if (newFoldername.includes("%")){
                        $("#createNewFolder").parent().addClass("error");
                        return;
                    }

                    if (currentFilelist.includes(newFoldername)){
                        //Current filelist already contain a folder with the same name
                        $("#createNewFolder").parent().addClass("error");
                        $("#newFolder").find(".duplicateWarning").show();
                        return;
                    }
                    //OK to proceed.
                    $("#createNewFolder").parent().removeClass("error").addClass("success");
                    $("#newFolder").find(".duplicateWarning").hide();
                    requestCSRFToken(function(token){
                        $.ajax({
                            url: "../../system/file_system/newItem",
                            data: {type: "folder", src: currentPath, filename: newFoldername, csrft: token},
                            success: function(data){
                                if (data.error !== undefined){
                                    msgbox("red remove",applocale.getString("message/" + data.error,data.error));
                                }else{
                                    msgbox("checkmark",applocale.getString("message/newfolder/success", "New folder created."));
                                    refreshList();
                                }
                                $("#newFolder").fadeOut('fast');
                                hideAllPopupWindows();
                                if (currentPath == "user:/"){
                                    //Reload the User root folder list
                                    initRootDirs();
                                }
                            }
                        });
                    });
                    
                }
            }


            function confirmNewFile(){
                var filename = $("#createNewFileName").val();
                if (filename == ""){
                    //Filename not set
                    $("#createNewFileName").parent().addClass("error");
                    return;
                }else if(currentFilelist.includes(filename)){
                    //File with this name already exists
                    $("#createNewFileName").parent().addClass("error");
                    $("#newFile").find(".duplicateWarning").show();
                    return;
                }
                $("#createNewFileName").parent().removeClass("error");
                //Ok to proceed
                requestCSRFToken(function(token){
                    $.ajax({
                        url: "../../system/file_system/newItem",
                        data: {type: "file", src: currentPath, filename:filename,csrft: token},
                        success: function(data){
                            if (data.error !== undefined){
                                msgbox("red remove",applocale.getString("message/" + data.error,data.error));
                            }else{
                                msgbox("checkmark",filename + applocale.getString("message/newItem/success", " created."));
                                refreshList();
                            }
                        }
                    });
                });
                
                hideAllPopupWindows();
                $("#newFile").fadeOut('fast');
            }

            //Open File Location
            function openFileLocation(){
                var folders = [];
                $(".selected.fileObject").each(function(){
                    var thisFilepath = $(this).attr('filepath');
                    var thisFilename = $(this).attr('filename');
                    openPathInNewWindow(encodeURIComponent(JSON.stringify([{
                        filename: thisFilename,
                        filepath: thisFilepath
                    }])))
                });
                
            }

            //OpenWith dialog
            function openWith(){
                if ($(".selected.fileObject").length == 0){
                    msgbox("question",applocale.getString("message/nofileSelected", "No file selected"));
                    return;
                }
                //Get a list of modules and append it into the selection list
                $.get("../../system/modules/list",function(data){
                    if (data.error !== undefined){
                        console.log(data.error);
                    }else{
                        $("#openWithModuleList").html("");
                        for (var i =0; i < data.length; i++){
                            var thisModule = data[i];
                            var supportFW = `<div class="ui horizontal mini icon label"><i class="window restore outline icon"></i> ${applocale.getString("opr/openwith/floatWindow", "Floating Window")}</div>`;
                            var supportEmb = `<div class="ui horizontal mini icon label"><i class="folder open icon"></i> ${applocale.getString("opr/openwith/embedded", "File Input")}</div>`;
                            if (!thisModule.SupportFW){
                                supportFW = "";
                            }
                            if (!thisModule.LaunchEmb){
                                supportEmb = "";
                            }
                            var launchInfo = encodeURIComponent(JSON.stringify(thisModule));
                            $("#openWithModuleList").append(`<div class="item selectable openWithModule" launchInfo="${launchInfo}" onclick="selectOpenWithModule(this, event);" ondblclick="selectOpenWithModule(this, event); openWithSelectedModule();">
                                <img class="ui avatar image" src="../../${thisModule.IconPath}">
                                <div class="content" style="padding-left:12px;">
                                    <div class="header">${thisModule.Name}</div>
                                    <div class="description">
                                        ${supportFW}
                                        ${supportEmb}
                                    </div>
                                </div>
                            </div>`);
                        }
                    }
                });
                $(".openWithModule.popupbuttons").addClass("disabled");
                
                hideAllPopupWindows();
                if (!ao_module_virtualDesktop){
                    $("#openWith").find(".vdonly").hide();
                }
                showPopupWrapper();
                $("#openWith").transition("slide left in");

            }

            //Functions for handling open with module selection and file opening
            function selectOpenWithModule(object, event){
                event.preventDefault();
                $(".openWithModule.popupbuttons").removeClass("disabled");
                $(".openWithModule.selected").removeClass("selected");
                $(object).addClass("selected");
            }

            function openWithSelectedModule(btn){
                if ($(btn).hasClass("disabled")){
                    return false;
                }
                var targetModuleInfo = JSON.parse(decodeURIComponent($(".openWithModule.selected").attr("launchInfo")));
                var targetObjects = $(".selected.fileObject");

                //Phrase launch mode from the module info
                var launchURL = targetModuleInfo.StartDir
                var launchSize = [undefined, undefined];
                var iconPath = targetModuleInfo.IconPath;
                var title = targetModuleInfo.Name;
                if (targetModuleInfo.SupportEmb){
                    //Launch with embedded mode
                    launchURL = targetModuleInfo.LaunchEmb;
                    if (targetModuleInfo.InitEmbSize !== null){
                        launchSize = targetModuleInfo.InitEmbSize
                    }
                   
                }else if (targetModuleInfo.SupportFW){
                    //Launch with floatWindow mode
                    launchURL = targetModuleInfo.LaunchFWDir;
                    if (targetModuleInfo.InitFWSize !== null){
                        launchSize = targetModuleInfo.InitFWSize
                    }
                }else if (targetModuleInfo.StartDir !== ""){
                    //Launch with default mode

                }else{
                    msgbox("red remove",applocale.getString("message/moduleNotSupport", "This module has no endpoint for opening a file."));
                    return;
                }   

                //Parse the filelist
                var filelist = [];
                $(targetObjects).each(function(){
                    var filename = $(this).attr("filename");
                    var filepath = $(this).attr("filepath");
                    filelist.push({
                        filename: filename,
                        filepath: filepath
                    });
                });

                fileHash = encodeURIComponent(JSON.stringify(filelist));
                if (ao_module_virtualDesktop){
                    //Open the target module in a new fw
                    parent.newFloatWindow({
                        url: launchURL + "#" + fileHash,
                        width: launchSize[0],
                        height: launchSize[1],
                        appicon: iconPath,
                        title: title
                    });
                }else{
                    //Redirect current window to the target module
                    window.location.href = "../../" + launchURL + "#" + fileHash;
                }

                hideAllPopupWindows();
            }

            function openFileWithModuleInNewTab(btn){
                if ($(btn).hasClass("disabled")){
                    return false;
                }
                var targetModuleInfo = JSON.parse(decodeURIComponent($(".openWithModule.selected").attr("launchInfo")));
                var targetObjects = $(".selected.fileObject");

                //Parse the filelist
                var filelist = [];
                $(targetObjects).each(function(){
                    var filename = $(this).attr("filename");
                    var filepath = $(this).attr("filepath");
                    filelist.push({
                        filename: filename,
                        filepath: filepath
                    });
                });

                //Directly passing the file information to the startdir
                fileHash = encodeURIComponent(JSON.stringify(filelist));
                console.log(targetModuleInfo);

                if (targetModuleInfo.StartDir == ""){
                    //Not a module supporting fw mode
                    if (targetModuleInfo.SupportEmb == true && targetModuleInfo.LaunchEmb != ""){
                        window.open("../../" + targetModuleInfo.LaunchEmb + "#" + fileHash);
                    }
                }else{
                    window.open("../../" + targetModuleInfo.StartDir + "#" + fileHash);
                }
                
                hideAllPopupWindows();
            }

            function openRawFileInFloatWindow(btn){
                //Directly open this (or more than one) files / folder in floatWindow
                var targetObjects = $(".selected.fileObject");
                $(targetObjects).each(function(){
                    if ($(this).attr("type") == "file"){
                        var launchURL = "media?file=" + $(this).attr('filepath');
                        parent.newFloatWindow({
                            url: launchURL,
                            appicon: "img/system/file.png",
                            title: $(this).attr('filename'),
                            "background-color": "#1f1f1f"
                        });
                    }else if ($(this).attr("type") == "folder"){
                        var launchURL = "SystemAO/file_system/file_explorer.html#" + $(this).attr("filepath");
                        parent.newFloatWindow({
                            url: launchURL,
                            appicon: "SystemAO/file_system/img/small_icon.png",
                            title: "File Manager - "  + $(this).attr('filename'),
                        });
                    }else{
                        //Not supported openeing type.
                        console.log("Failed to open file " + $(this).attr('filepath') + " . WIP")
                    }
                });
                hideAllPopupWindows();
            }

            //Open the filepaths in the given paramters
            function openPathWithDefaultOpener(filepaths){
                console.log("Opening: ", filepaths);
                for (var i =0; i < filepaths.length; i++){
                    let filepath = JSON.parse(JSON.stringify(filepaths[i]));
                    var ext = "." + filepath.split(".").pop();
                    $.ajax({
                        url: "../../system/modules/getDefault",
                        method: "GET",
                        data: {opr: "launch", ext: ext, mode: "launch"},
                        success: function(data){
                            if (data.error !== undefined){
                                //No default opener assigned. Launch it with opener selector
                                var url = "SystemAO/file_system/defaultOpener.html";
                                var icon = "SystemAO/file_system/img/opener.png";
                                var title = "Select an opener WebApp: "
                                var openFileList = [];
                                var openFileObject = {
                                    filepath: filepath,
                                    filename: filepath.split("/").pop()
                                }
                                openFileList.push(openFileObject);
                                var openParamter = encodeURIComponent(JSON.stringify(openFileObject));
                                var ao_module_virtualDesktop = !(!parent.isDesktopMode);
                                console.log(window.innerHeight/2 - 510/20);
                                if (ao_module_virtualDesktop){
                                    parent.newFloatWindow({
                                        url: url + "#" + openParamter,
                                        width: 320,
                                        height: 510,
                                        appicon: icon,
                                        title: title
                                    });
                                }else{
                                    url = "defaultOpener.html";
                                    window.open(url + "#" + openParamter);
                                }
                            }else{
                                //Assigned. Launch with given paramter
                                var url = data["StartDir"];
                                var size = [undefined, undefined];
                                var title = data["Name"];
                                var icon = "img/system/favicon.png";
                                if (data["IconPath"] != ""){
                                    icon = data["IconPath"];
                                }
                                //Use floatWindow if exists
                                if (data["SupportFW"] == true && data["LaunchFWDir"] != ""){
                                    url = data["LaunchFWDir"];
                                    if (data["InitFWSize"] !== null){
                                        size = data["InitFWSize"]
                                    }
                                }
                                //Use embedded mode if exists
                                if (data["SupportEmb"] == true && data["LaunchEmb"] != ""){
                                    url = data["LaunchEmb"];
                                    if (data["InitEmbSize"] !== null){
                                        size = data["InitEmbSize"]
                                    }
                                }

                                //Build open File Hash Data Format
                                var openFileList = [];
                                var openFileObject = {
                                    filepath: filepath,
                                    filename: filepath.split("/").pop()
                                }
                                openFileList.push(openFileObject);
                                var openParamter = encodeURIComponent(JSON.stringify(openFileList));
                                
                                //Add launch files info and launch floatWindow
                                var ao_module_virtualDesktop = !(!parent.isDesktopMode);
                                if (ao_module_virtualDesktop){
                                    parent.newFloatWindow({
                                        url: url + "#" + openParamter,
                                        width: size[0],
                                        height: size[1],
                                        appicon: icon,
                                        title: title
                                    });
                                }else{
                                    window.open("../../" + url + "#" + openParamter);
                                }
                                
                            }
                        }
                    });
                }
            }

            function openSelectedFolderInNewWindow(){
                $(".fileObject.selected").each(function(){
                    if ($(this).attr("type") == "folder"){
                        console.log($(this).attr('filepath'));
                        openPathInNewWindow([$(this).attr('filepath')]);
                    }
                })
            }

            function openSelectedVroot(){
                $("#storageroot").find(".dir.item").each(function(){
                    if ($(this).hasClass("active")){
                        var thisRootPath = $(this).attr('filepath');
                        openPathInNewWindow([$(this).attr('filepath')]);
                    }
                });
            }

            //Always open the first object locally, and open others in new floatWindows
            function openFolderInNewWindow(paths){
                if (paths.length > 0){
                    listDirectory(paths[0]);
                    for (var i = 1; i < paths.length; i++){
                        //newFloatWindow(location.href.replace(location.hash,"") + "#" + path[i])
                        openPathInNewWindow(paths[i]);
                    }
                }
            }

            function openPathInNewWindow(path){
                console.log("Opening in new File Maanger: ", window.location.pathname + "#" + path);
                ao_module_newfw({
                    url: window.location.pathname + "#" + path,
                    appicon: "SystemAO/file_system/img/small_icon.png",
                    title: "File Manager",
                    width: 1080,
                    height: 580,
                    parent: ao_module_windowID,
                });
            }

            //Preference setting and loading functions.
            function setPreference(key, value){
                $.ajax({
                    url:"../../system/file_system/preference?key=" + key + "&value=" + value,
                    success: function(data){
                        if (data.error !== undefined){
                            console.log(data);
                        }
                    }
                });
            }

            function loadPreference(key, callback){
                $.get("../../system/file_system/preference?key=" + key,function(data){
                    callback(data);
                });
            }

            // ============================== WINDOW RESIZE FUNCTIONS =====================
            $(window).on("resize",function(){
                initWindowSizes(false);
                if (!isMobile && window.innerWidth < 620 && sideBarShown == true){
                    toggleSidebar(false);
                }else if (!isMobile && window.innerWidth > 650 && sideBarShown == false){
                    toggleSidebar(false);
                }

                if (isMobile && !pathInputMode){
                    //refreshList();
                }

                //Resize the share iframe
                resizeShareIframe()

                //Resize the path display content
                if (!pathInputMode){
                    updatePathDisplay(currentPath);
                }
                
            });

            function handleShareFilebuttonClick(event, object){
                event.preventDefault(); 
                event.stopImmediatePropagation();
                $(".fileObject.selected").removeClass("selected");
                if (viewMode == "list"){
                    $(object).parent().parent().addClass("selected");
                }else if (viewMode == "grid"){
                    $(object).parent().parent().parent().addClass("selected");
                }else if (viewMode == "details"){
                    $(object).parent().parent().addClass("selected");
                }
               
                shareFile();
            }

            function resizeShareIframe(){
                $("#shareFileEmbedded").css("height", $("#shareFile").height() - 126 + "px");
            }
            
            function shareFile(){
                var selectedFiles = [];
                var selectedFileObjects = [];
                $(".fileObject.selected").each(function(){
                    var thisFilepath = $(this).attr("filepath");
                    var thisFilename = $(this).attr("filename");
                    selectedFiles.push(thisFilepath);
                    selectedFileObjects.push({"filepath": thisFilepath, "filename": thisFilename});
                });

                if (selectedFiles.length == 0){
                    msgbox("question", applocale.getString("message/No file selected", "No file selected"));
                    console.log("No file is selected for sharing");
                    return;
                }else if (selectedFiles.length > 1){
                    //Try to share more than 1 files, which is not supported
                    msgbox("yellow exclamation", applocale.getString("message/Multiple files share is currently not supported", "Multiple files share is currently not supported"));
                    console.log("Multi share is current not supported");
                    return
                }

                //OK! Continue to generate link
                var selectedFile = selectedFiles[0];
                var selectedFileObject = selectedFileObjects[0];
                shareEditingObject = selectedFile;
                $.ajax({
                    url: "../../system/file_system/share/new",
                    data: {path: selectedFile},
                    success: function(data){
                        if (data.error !== undefined){
                            msgbox("red remove",applocale.getString("message/" + data.error,data.error), 5000);
                        }else{
                            //Build the predicted share endpoint
                            selectedFileObject["QRCode"] = true;
                            selectedFileObject["ActionButtons"] = false;
                            var payload = encodeURIComponent(JSON.stringify([selectedFileObject]));
                            var requestURL = "file_share.html#" + payload;
                            console.log(selectedFileObject, requestURL);
                            $("#shareFileEmbedded").attr("src", requestURL);
                            resizeShareIframe();

                            //Show the share file interface
                            hideAllPopupWindows();
                            showPopupWrapper();
                            $("#shareFile").transition('slide left');

                            //Reload the list
                            listDirectory(currentPath);
                        }
                      
                    }
                });
               
            }

            function removeSharing(){
                if (shareEditingObject == ""){
                    return
                }

                //The target file to remove
                var selectedFile = shareEditingObject;
                $("#shareFileEmbedded").attr("src", "");
                $.ajax({
                    url: "../../system/file_system/share/delete",
                    data: {vpath: selectedFile},
                    success: function(data){
                        console.log(data);
                        $("#qrcode").html(`<img src="img/private.png">`);
                        $(".shareoption").parent().addClass("disabled");
                        $("#sharelink").text("(Sharing Removed)");
                        $("#sharelink").removeAttr("href");
                        //Reload the current filelist and hide the share interface
                        listDirectory(currentPath);

                        //Reset sharing file settings
                        shareEditingObject = ""
                        shareEditingUUID = ""
                    }
                });

                hideAllPopupWindows();
                msgbox("checkmark", applocale.getString("message/share/removed", "File share removed"))
            }

            function updateShareSettings(object){
                $(object).addClass("loading");
                var shareMode = $("#shareSettingForm [name='shareopt']:checked").val();
                $.ajax({
                    url: "../../system/file_system/share/edit",
                    data: {uuid: shareEditingUUID, mode: shareMode},
                    success: function(data){
                        if (data.error !== undefined){
                            alert(data.error);
                        }
                        $(object).removeClass("loading");
                        $(object).html(`<i class="checkmark icon"></i> Updated`);
                        $(object).addClass("positive");
                        setTimeout(function(){
                            $(object).html("Update");
                            $(object).removeClass("positive");
                        }, 3000);
                    }
                })
            }

            function hideShare(){
                hideAllPopupWindows();
                $("#shareFileEmbedded").attr("src", "");
            }

            function exitMultiSelectMode(){
                if (ctrlHold){
                    ctrlHold = false;
                    updateCtrlDisplay();
                }
            }

            function toggleMobileSidebar(show=undefined, callback=undefined){
                if(show == true){
                    $("#mobileNaviBar").stop().finish().show();
                }else if (show == false){
                    $("#mobileNaviBar").stop().finish().hide();
                }else{
                    $("#mobileNaviBar").toggle();
                }

                if (callback != undefined){
                    setTimeout(callback, 300);
                }
            }

            function toggleSidebar(useAnimation=true){
                //Fixing desktop bugs on showing the sidebar
                if (isMobile){
                    if (sideBarShown){
                        $("#directorySidebar").hide();
                    }else{
                        $("#directorySidebar").show();
                    }
                    
                }else{
                    if (sideBarShown){
                        $("#directorySidebar").stop().finish().transition("slide right out", function(){
                            $("#directorySidebar").hide();
                        });
                        //$("#directorySidebar").stop().finish().animate({left: 0},200);
                    }else{
                        $("#directorySidebar").stop().finish().transition("slide right in", function(){
                            $("#directorySidebar").show();
                        });
                        //$("#directorySidebar").stop().finish().animate({left: -1 * directorySidebarWidth},200);
                    }
                }
               
                sideBarShown = !sideBarShown;
                initWindowSizes(useAnimation);
            }

            function initWindowSizes(animate=true){
                var h = $("#navibar").css("height");
                var hint = $("#navibar").height();
                //$("#mainWindow").css("padding-top",h);
                var windowHeight = window.innerHeight - hint - 12;
                //console.log(windowHeight);
                if (sideBarShown){
                    //Resize the sidebar 
                    $("#directorySidebar").css("top",h);
                    $("#directorySidebar").css("width",directorySidebarWidth);
                    $("#directorySidebar").css("height",windowHeight + "px");
                    //Resize the file viewer
                    $("#folderView").css("top",h);
                    /*
                    if (window.innerWidth > 650){
                        if (animate){
                            $("#folderView").stop().finish().animate({
                                left: directorySidebarWidth + 'px',
                                width: window.innerWidth - directorySidebarWidth - 2 + "px"
                            },200);
                        }else{
                            $("#folderView").css({
                                left: directorySidebarWidth + 'px',
                                width: window.innerWidth - directorySidebarWidth - 2 + "px"
                            });
                        }
                    }else{
                        //Window width too small to allow resizing sidebar shown. Overlap it
                        if (animate){
                            $("#folderView").stop().finish().animate({
                                left: directorySidebarWidth + 'px',
                                width: window.innerWidth + "px"
                            },200);
                        }else{
                            $("#folderView").css({
                                left: directorySidebarWidth + 'px',
                                width: window.innerWidth + "px"
                            });
                        }
                    }
                    */
                   
                    if (isChromium){
                        //$("#mainWindow").css("height", window.innerWidth);
                    }
                    //$("#folderView").css("left",directorySidebarWidth + "px");
                    $("#folderView").css("height",windowHeight + "px");
                }else{
                    $("#folderView").css("top",h);
                    if (animate){
                        $("#folderView").stop().finish().animate({
                            left:'0px',
                            width:(window.innerWidth - 2 + "px")
                        },200);
                    }else{
                        $("#folderView").css({
                            left:'0px',
                            width:(window.innerWidth - 2 + "px")
                        });
                    }
                    $("#folderView").css("height",windowHeight + "px");
                }

                $("#propertiesView").css("height", windowHeight + "px");
            }

            function toggleDarkTheme(){
                if ($(".darkTheme").length > 0){
                    //Set To whiteTheme
                    $("body").removeClass("darkTheme").addClass("whiteTheme");
                    currentTheme = "whiteTheme";
                    $("#darkthemebtn").attr("class","moon icon");
                    $("#darkthemebtn").parent().addClass("inverted");
                    $(".dropdown").removeClass("inverted");
                    setPreference("file_explorer/theme","whiteTheme");
                    $("#mobileNaviBar").removeClass("inverted");
                    $("#darkthemebtn").css("color", "#dadada");
                    
                    //If in vdi mode, update desktop's listMenu as well
                    if (ao_module_virtualDesktop){
                        parent.initTheme("whiteTheme");
                    }
                }else{
                    //Set to DarkTheme
                    $("body").removeClass("whiteTheme").addClass("darkTheme");
                    currentTheme = "darkTheme";
                    $("#darkthemebtn").attr("class","sun icon");
                    $("#darkthemebtn").parent().removeClass("inverted");
                    $("#darkthemebtn").css("color", "#3d3f47");
                    $(".dropdown").addClass("inverted");
                    setPreference("file_explorer/theme","darkTheme");
                    $("#mobileNaviBar").addClass("inverted");
                    
                     //If in vdi mode, update desktop's listMenu as well
                     if (ao_module_virtualDesktop){
                        parent.initTheme("darkTheme");
                    }
                }
               
            }

            function msgbox(icon, text, delay=3000){
                $($(".msgbox").find("span")[0]).text(text);
                $($(".msgbox").find("i")[0]).attr("class", icon + " icon");
                $(".msgbox").stop().finish().slideDown('fast').delay(delay).slideUp('fast', function(){
                    initWindowSizes(false);
                });
            }

            

            //Keyboard hotkey events
            $(document).keydown(function(event){
                if ($(':focus').is("input")){
                    //Do not block operations on input fields.
                    if (event.which == 27){
                        //Cancel the operation
                        if (searchMode){
                            //Exit search mode
                            hideSearchBar();
                        }else if (pathInputMode){
                            //Path input mode. Hide the path input
                            hideManualOpenPathInput();
                        }
                    }
                    return;
                }
                if(event.which==17 || event.which == 91){
                    ctrlHold = true;
                    updateCtrlDisplay();
                }else if (event.which == 16){
                    shiftHold = true;
                    updateCtrlDisplay();
                }else if (event.which == 67 && ctrlHold == true){
                    //Ctrl + C
                    if (!$(".popup").is(":visible")){
                        if ($(lastClickedElement).closest("#propertiesView").length > 0){
                            //Inside the file properties View
                            return;
                        }
                        event.preventDefault();
                        copy();
                    } 
                }else if (event.which == 88 && ctrlHold == true){
                    //Ctrl + X
                    if (!$(".popup").is(":visible")){
                        if ($(lastClickedElement).closest("#propertiesView").length > 0){
                            //Inside the file properties View
                            return;
                        }
                        event.preventDefault();
                        cut();
                    }
                }else if (event.which == 65 && ctrlHold == true){
                    //Ctrl + A
                    if ($(lastClickedElement).closest("#propertiesView").length > 0){
                        //Inside the file properties View
                        return;
                    }
                    event.preventDefault();
                    $(".fileObject").addClass("selected");
                    updateSelectedObjectsCount();
                }else if (event.which == 78 && shiftHold == true){
                    //Shift + N, Open new file manager window with current path
                    event.preventDefault();
                    openPathInNewWindow(currentPath);

                }else if (event.which == 86 && ctrlHold == true){
                    if (!$(".popup").is(":visible")){
                        if ($(lastClickedElement).closest("#propertiesView").length > 0){
                            //Inside the file properties View
                            return;
                        }
                        paste();
                    } 
                }else if (event.which == 46 && shiftHold == true){
                    //Shift + delete
                    forceDelete();
                }else if (event.which == 46){
                    //Delete
                    deleteFile();
                }else if (event.which == 38){
                    //Up Arrow
                    if ($(".popup:visible").length == 0){
                        //No popup visiable
                        if (ctrlHold == true){
                            //Parenet path
                            parentDir();
                        }else{
                            //Select the file on the upper
                            selectPreviousFile(event);
                        }
                    }
                }else if (event.which == 40){
                    //Down arrow
                    if ($(".popup:visible").length == 0){
                        //No popup visiable
                        selectNextFile(event);
                    }
                }else if (event.which == 39){
                    //Right arrow
                    if ($(".popup:visible").length == 0 && viewMode == "grid"){
                        //No popup visiable and grid mode
                        selectRightFile(event);
                    }
                }else if (event.which == 37){
                    //Left arrow
                    if ($(".popup:visible").length == 0 && viewMode == "grid"){
                        //No popup visiable and grid mode
                        selectLeftFile(event);
                    }
                }else if (event.which == 13){
                    //Enter key
                    if ($(".fileObject.selected").length > 0){
                        openViaButton();
                    }else if ($(".fileObject.hotSearchHighlight").length > 0 && $(".fileObject.selected").length == 0){
                        //Hot search selection mode

                    }
                }else if (event.which == 27){
                    //Esc key
                    hideAllPopupWindows();
                    $(".fileObject.selected").removeClass("selected");

                }else{
                    //Handle generic file search by consecutive typing
                    if (hotSearchTimer != null){
                        clearTimeout(hotSearchTimer);
                    }
                    $(".fileObject.selected").removeClass("selected");
                    hotSearchTimer = setTimeout(function(){
                        exitHotSearch();
                    }, 1000);

                    if (hotSearchBuffer.length > 0 && event.key == hotSearchBuffer.substr(hotSearchBuffer.length - 1, 1)){
                        //Jump to next result
                        hotSearchOffsetIndex++;
                    }else{
                        hotSearchOffsetIndex = 0;
                        hotSearchBuffer+= event.key;
                    }
                   
                    handleHotSearch(hotSearchBuffer, hotSearchOffsetIndex);
                }
            });

            $(document).keyup(function(event){
                if(event.which==17 || event.which == 91){
                    ctrlHold = false;
                    updateCtrlDisplay();
                }else if (event.which == 16){
                    shiftHold = false;
                }
            });

            $("#directorySidebar").on("click",function(evt){
                //Clear the button holding
                $(".fileObject.selected").removeClass("selected");
                shiftHold = false;
                ctrlHold = false;
                updateCtrlDisplay();

                if (renameMode){
                    exitRenameModeWithConfirm();
                }
            });

            //Check if localstorage is availble
            function lscheck(){
                var test = 'test';
                try {
                    localStorage.setItem(test, test);
                    localStorage.removeItem(test);
                    return true;
                } catch(e) {
                    return false;
                }
            }

            function selectNextFile(e){
                e.preventDefault();
                //Check if there are no selection. If yes, select the first file object
                if ($(".fileObject.selected").length == 0 && $(".fileObject").length > 0){
                    //Select the first file object
                    $($(".fileObject")[0]).addClass("selected");
                    return
                }else if ( $(".fileObject").length == 0){
                    //No file in this folder
                    return
                }

                //Already contain selected file on the interface. Seleect it
                var baseObject = $($(".fileObject.selected")[0]);
                if ($(".fileObject.selected").length > 1){
                    $(".fileObject.selected").removeClass("selected");
                }
                if (viewMode == "list" || viewMode == "details"){
                    //Select the next file
                    var nextObject = $(".fileObject").eq( $(".fileObject").index( $(baseObject) ) + 1 );
                    if (nextObject.length > 0){
                        nextObject.addClass("selected");
                        scrollToFileObject(nextObject);
                        $(baseObject).removeClass("selected");
                    }
                }else if (viewMode == "grid"){
                    var colobj = getFileObjectInTheSameCol(baseObject);
                    var nextObject = baseObject;
                    for (var i = 0; i < colobj.length; i++){
                        if ($(colobj[i]).hasClass("selected") && i != colobj.length - 1){
                            nextObject = colobj[i + 1];
                        }
                    }

                    $(baseObject).removeClass("selected");
                    nextObject.addClass("selected");
                    scrollToFileObject(nextObject);
                }

                if (propertiesView){
                    let selectedFile = $(".fileObject.selected")[0];
                    let filepath = $(selectedFile).attr('filepath');
                    loadFileProperties(filepath);
                }
                
            }

            function selectPreviousFile(e){
                e.preventDefault();
                //Check if there are no selection. If yes, select the first file object
                if ($(".fileObject.selected").length == 0 && $(".fileObject").length > 0){
                    //Select the first file object
                    $($(".fileObject")[$(".fileObject").length - 1]).addClass("selected");
                    return
                }else if ( $(".fileObject").length == 0){
                    //No file in this folder
                    return
                }

                var baseObject = $($(".fileObject.selected")[0]);
                if ($(".fileObject.selected").length > 1){
                    $(".fileObject.selected").removeClass("selected");
                }
                if (viewMode == "list" || viewMode == "details"){
                    //Select the previous file
                    if ($(".fileObject").index( $(baseObject) ) -1 < 0){
                        return;
                    }
                    var previousObject = $(".fileObject").eq( $(".fileObject").index( $(baseObject) ) -1 );
                    if (previousObject.length > 0){
                        previousObject.addClass("selected");
                        scrollToFileObject(previousObject);
                        $(baseObject).removeClass("selected");
                    }
                    
                
                }else if (viewMode == "grid"){
                    var colobj = getFileObjectInTheSameCol(baseObject);
                    var prevObj = baseObject;
                    for (var i = 0; i < colobj.length; i++){
                        if ($(colobj[i]).hasClass("selected") && i > 0){
                            prevObj = colobj[i - 1];
                        }
                    }

                    $(baseObject).removeClass("selected");
                    prevObj.addClass("selected");
                    scrollToFileObject(prevObj);
                }

                if (propertiesView){
                    let selectedFile = $(".fileObject.selected")[0];
                    let filepath = $(selectedFile).attr('filepath');
                    loadFileProperties(filepath);
                }
            }

            function scrollToFileObject(fileObject){
                if (viewMode == "grid"){
                    $('#folderView').scrollTop($(fileObject)[0].offsetTop - ($("#directorySidebar").height()/2 - 340));
                }else{
                    $('#folderView').scrollTop($(fileObject)[0].offsetTop - ($("#directorySidebar").height()/2 - 140));
                }
            }

            //Grid mode left right opr
            function selectLeftFile(e){
                e.preventDefault();
                if (viewMode != "grid"){
                    return;
                }

                if ($(".fileObject.selected").length == 0 && $(".fileObject").length > 0){
                    //Select the first file object
                    $($(".fileObject")[$(".fileObject").length - 1]).addClass("selected");
                    return
                }else if ( $(".fileObject").length == 0){
                    //No file in this folder
                    return
                }

                var baseObject = $($(".fileObject.selected")[0]);
                if ($(".fileObject").index( $(baseObject) ) -1 < 0){
                    return;
                }
                var previousObject = $(".fileObject").eq( $(".fileObject").index( $(baseObject) ) -1 );
                if (previousObject.length > 0){
                    previousObject.addClass("selected");
                    scrollToFileObject(previousObject);
                    $(baseObject).removeClass("selected");
                }

                if (propertiesView){
                    let selectedFile = $(".fileObject.selected")[0];
                    let filepath = $(selectedFile).attr('filepath');
                    loadFileProperties(filepath);
                }
            }

            function selectRightFile(e){
                e.preventDefault();
                if (viewMode != "grid"){
                    return;
                }
                
                if ($(".fileObject.selected").length == 0 && $(".fileObject").length > 0){
                    //Select the first file object
                    $($(".fileObject")[0]).addClass("selected");
                    return
                }else if ( $(".fileObject").length == 0){
                    //No file in this folder
                    return
                }

                var baseObject = $($(".fileObject.selected")[0]);
                var nextObject = $(".fileObject").eq( $(".fileObject").index( $(baseObject) ) + 1 );
                if (nextObject.length > 0){
                    nextObject.addClass("selected");
                    scrollToFileObject(nextObject);
                    $(baseObject).removeClass("selected");
                }

                if (propertiesView){
                    let selectedFile = $(".fileObject.selected")[0];
                    let filepath = $(selectedFile).attr('filepath');
                    loadFileProperties(filepath);
                }
            }

            //Functions for getting file objects in the same collume
            function getFileObjectInTheSameCol(baseFileObject){
                if (viewMode != "grid"){
                    return;
                }

                var baseOffset = $(baseFileObject).offset().left;
                var fileObjectInTheSameCol = [];
                $(".fileObject").each(function(){
                    if ($(this).offset().left == baseOffset){
                        let thisFileObject = $(this);
                        fileObjectInTheSameCol.push(thisFileObject);
                    }
                });

                return fileObjectInTheSameCol;

            }

            //Function for getting file objects in the same row
            function getFileObjectInTheSameRow(baseFileObject){
                if (viewMode != "grid"){
                    return;
                }

                var baseOffset = $(baseFileObject).offset().top;
                var fileObjectInTheSameRow = [];
                $(".fileObject").each(function(){
                    if ($(this).offset().top == baseOffset){
                        let thisFileObject = $(this);
                        fileObjectInTheSameRow.push(thisFileObject);
                    }
                });
                
                return fileObjectInTheSameRow;
            }

            //Handle drag drop upload
           function drop(event){
                event.preventDefault();
                console.log(event, event.target)
                //Check if this is file upload or file move / copy function
                let dt = event.dataTransfer
                let files = dt.files
                if (files.length > 0){
                    //Upload file via dragdrop
                    msgbox("upload",applocale.getString("message/upload/started", "Upload Started"));
                    let items = event.dataTransfer.items;
                    for (let i=0; i<items.length; i++) {
                        let item = items[i].webkitGetAsEntry();
                        if (item) {
                            recursiveScanFilesUpload(item);
                        }
                    }
                    
                }else{
                    //File transfer within system
                    let filedata = event.dataTransfer.getData("filedata");
                    if (filedata != ""){
                        try{
                            let fileList = JSON.parse(filedata);
                            //Check if the file objects are from the same host
                            let localFiles = [];
                            let remoteFiles = [];
                            fileList.forEach(file => {
                                if (file.hostUUID == systemUUID){
                                    //Local file
                                    localFiles.push(file);
                                }else{
                                    //Remote files
                                    remoteFiles.push(file);
                                }
                            });

                            //Start processing the local files
                            let currentVroot = currentPath.split(":/").shift();
                            clipboard = [];

                            //Assume all files are from the same directory
                            if (localFiles.length > 0){
                                //Check if drag drop from the same directory
                                let currentDirname = currentPath.split("/")
                                currentDirname.pop();
                                currentDirname = currentDirname.join("/");
                                let firstFileDirname = localFiles[0].filepath.split("/")
                                firstFileDirname.pop();
                                firstFileDirname = firstFileDirname.join("/");
                                if (currentDirname == firstFileDirname){
                                    //Drag start and drop location are the same directory
                                    msgbox("red remove",applocale.getString("message/destIdentical", "Source and destination file names are the same"));
                                    return;
                                }

                                let fileVroot = localFiles[0].filepath.split(":/").shift();
                                if (currentVroot == fileVroot){
                                    //Same device same root. Move the file
                                    cutMode = true;
                                }else{
                                    //Same device differnet root. Copy the file
                                    cutMode = false;
                                }

                                //Move all localFiles into clipboard
                                localFiles.forEach(file => {
                                    clipboard.push(file.filepath);
                                });

                                if (useLocalstorage){
                                    localStorage.setItem("ao/file_system/clipboard",JSON.stringify(clipboard));
                                    if (cutMode){
                                        localStorage.setItem("ao/file_system/cutmode","true");
                                    }else{
                                        localStorage.setItem("ao/file_system/cutmode","false");
                                    }
                                    
                                }

                                //Paste all the files to the current path
                                console.log(clipboard);
                                paste();
                            }
                           
                            

                        }catch(ex){
                            console.log(ex);
                            msgbox("red remove",applocale.getString("message/decodeFilelistFail", "File drop failed. Unable to decode filelist."));
                        }
                    }
                    
                    
                }
                
           }


           function recursiveScanFilesUpload(item, rootpath="", base=""){
               var filesInside = [];
                if (item.isDirectory) {
                    //This is a directory
                    let directoryReader = item.createReader();
                        directoryReader.readEntries(function(entries) {
                        entries.forEach(function(entry) {
                            recursiveScanFilesUpload(entry, rootpath + item.name + "/", base);
                        });
                    });
                }else{
                    //This is a file. Upload it
                    item.file(function(fileObject){
                        if (isChrome || isSafari){
                            //WebKits
                            console.log("Upload Target", fileObject, rootpath);
                            uploadFile(fileObject, undefined, currentPath + rootpath);
                        
                        }else{
                            //Firefox. Special handling for root path.
                           
                            //Updates for Firefox 84.0.2 (64-bit), which changed minor implementation on relative path in folder updates
                            //This section of code is deprecated since then
                            /*
                                //As firefox will keep its file input relative path, we need to remove the root folder
                                //name from the rootpath passed in by the webkit API
                                
                                if (rootpath.substr(rootpath.length - 1, 1) == "/"){
                                    rootpath = rootpath.substr(0, rootpath.length - 1);
                                }
                                var rootpathInfo = rootpath.split("/");
                                if (rootpathInfo.length > 1){
                                    //Uploading folder to folder. Extract the folder root name
                                    rootpathInfo.pop();
                                }else{
                                    //Uploading file to folder. Do nothing
                                }
                                rootpath = rootpathInfo.join("/") + "/";

                                console.log("Upload Target", fileObject, rootpath);
                                uploadFile(fileObject, undefined, currentPath + rootpath);
                            */
                            //console.log(currentPath + rootpath);
                            uploadFile(fileObject, undefined, currentPath + base);
                        }
                        
                    });
                }
                return filesInside;
            }

        function showCurrentDirectoryProperties(){
            var fileList = [currentPath];
            console.log(fileList);
            var hashPassthrough = encodeURIComponent(JSON.stringify(fileList));
            ao_module_newfw({
                url: "SystemAO/file_system/file_properties.html#" + hashPassthrough,
                width: 340,
                height: 480,
                appicon: "SystemAO/file_system/img/properties.png",
                title: "File Properties",
            });
        }

        function showVrootProperties(){
            var rootname = [$("#storageroot").find(".dir.item.active").attr("filepath")];
            var hashPassthrough = encodeURIComponent(JSON.stringify(rootname));
            ao_module_newfw({
                url: "SystemAO/disk/diskprop.html#" + hashPassthrough,
                width: 420,
                height: 580,
                appicon: "img/system/drive.svg",
                title: "Disk Properties",
            });
        }

        function showSharesManager(){
            var rootname = [$("#storageroot").find(".dir.item.active").attr("filepath")];
            var hashPassthrough = encodeURIComponent(JSON.stringify(rootname));
            ao_module_newfw({
                url: "SystemAO/file_system/sharelist.html#" + hashPassthrough,
                width: 420,
                height: 580,
                appicon: "img/system/share.svg",
                title: "Shares Manager"
            });
        }

        function openBackupManager(){
            var rootname = [$("#storageroot").find(".dir.item.active").attr("filepath")];
            var hashPassthrough = encodeURIComponent(JSON.stringify(rootname));
            ao_module_newfw({
                url: "SystemAO/disk/disk_restore.html#" + hashPassthrough,
                width: 410,
                height: 580,
                appicon: "img/system/backup.svg",
                title: "Backup & Restore",
            });
        }

        function showFileProperties(){
            //Show the file list of the selected files
            if ($(".fileObject.selected").length > 0){
                //Build the filelist
                var fileList = [];
                $(".fileObject.selected").each(function(){
                    var filepath = $(this).attr("filepath");
                    fileList.push(filepath);
                });

                var hashPassthrough = encodeURIComponent(JSON.stringify(fileList));
                ao_module_newfw({
                    url: "SystemAO/file_system/file_properties.html#" + hashPassthrough,
                    width: 340,
                    height: 480,
                    appicon: "SystemAO/file_system/img/properties.png",
                    title: "File Properties",
                });
            }

            
        }

        function initUploadMode(){
            //Deprecated, will automatically decide which mode to use base on file size and disk space
            /*
            //Get the amount of RAM on the server side to check if low memory mode should be used.
            $.ajax({
                url: "../../system/info/getRAMinfo",
                success: function(data){
                    if (data.error !== undefined){
                        //Permission denied or other reasons that cannot access harwdare info. Use default mode
                        lowMemoryMode = true;
                    }else{
                        //Check if ramsize > 3.8GB. If yes, switch to large memory upload mode
                        var memsize = JSON.parse(data);
                        if (parseFloat(memsize)/ 1024 / 1024 / 1024 >= 3.8){
                            console.log("[File Explorer] Entering large memory upload mode")
                            lowMemoryMode = false;
                        }
                    }
                },
                error: function(){
                    //Hardware mode disabled. Always use low memory upload mode instead
                    lowMemoryMode = true;
                }
            });
            */

            //Get the avaible space on tmp disk and decide the cutoff file size that need to directly write to disk
            $.ajax({
                url: "../../system/disk/space/tmp",
                method: "POST",
                data: {},
                success: function(data){
                    if (data.error !== undefined){
                        console.log("[File Explorer] Unable to auto-detect huge file cutoff size: " + data.error);
                    }else{
                        if (!isNaN(data.Available) && data.Available > 0){
                            largeFileCutoffSize = data.Available/16 - 4096;
                            console.log("[File Explorer] Setting huge file cutoff size at: " + ao_module_utils.formatBytes(data.Available/16));
                        }else if (isNaN(data.Available)){
                            console.log("[File Explorer] Unable to read available tmp disk size. Using default huge file cutoff size.");
                        }
                        
                    }
                },
                error: function(){
                    //Hardware mode disabled. Use default value.
                }
            });
        }
       
        function uploadFile(file, uuid=undefined, targetDir=undefined) {
            if (file.size > postUploadModeCutoff && lowMemoryMode){
                 /*
                    Low Memory Upload Mode
                */
                var filename = encodeURIComponent(file.name);
                var filesize = file.size;

                //Generate a new file item
                let taskUUID = uuid;    //For queueing objects
                if (taskUUID == undefined){
                    //If this is a new file to be uploaded
                    taskUUID = appendUploadFileItem(file.name, file.size);
                    setTimeout(function(){
                        updateUploadFileCount();
                    }, 100);
                }

                //Push to upload pending list if the max concurrent upload is reached
                if (uploadingFileCount >= maxConcurrentUpload){
                    let uploadDir = currentPath;
                    if (targetDir !== undefined){
                        uploadDir = targetDir;
                    }else if (isFirefox && uploadDir == currentPath && file.webkitRelativePath != ""){
                        //Use the webkitRelativePath instead of the name, this is a folder upload
                        //Deprecated for Firefox 84.0.2 updates
                        /*
                        let pathinfo = file.webkitRelativePath.split("/");
                        pathinfo.pop();
                        let subpath = pathinfo.join("/");
                        uploadDir = uploadDir + subpath;
                        */
                        uploadDir = targetDir;
                    }
                    uploadPendingList.push({
                        File: file,
                        UUID: taskUUID,
                        TargetDir: JSON.parse(JSON.stringify(uploadDir)),
                    });
                    return
                }

                function updateProgressForWebSocketUpload(uuid, progress){
                    $(".uploadTask").each(function(){
                        if ($(this).attr("taskID") == uuid){
                            //Update this progress bar
                            $(this).find(".bar").css("width",progress + "%");
                            $(this).find(".progress.percentage").html(`<i class="ui upload icon"></i> ${progress.toFixed(1)}%`);
                            //console.log(progress.toFixed(1) + "%");
                            if (progress == 100){
                                //When progress = 100 and the server is not response with 200,
                                //That means the upload has finish and server is processing the upload
                                $(this).find(".progress").addClass("indicating");
                                //$(this).find(".progress.percentage").hide();
                            }
                        }
                    });
                }

                //Open the websocket
                let path = currentPath;
                let protocol = "wss://";
                if (location.protocol !== 'https:') {
                    protocol = "ws://";
                }

                var port = window.location.port;
                if (window.location.port == ""){
                    if (location.protocol !== 'https:') {
                        port = "80";
                    }else{
                        port = "443";
                    }
                }

                let uploadDir = currentPath;
                if (targetDir !== undefined){
                    //Not uploading to current directory. Change upload path to target
                    uploadDir = targetDir;
                }

                //Fixing Firefox path issues on or above FF48.0
                if (isFirefox && file.webkitRelativePath != ""){
                    //Use the webkitRelativePath instead of the name, this is a folder upload
                    let pathinfo = file.webkitRelativePath.split("/");
                    pathinfo.pop();
                    let subpath = pathinfo.join("/");
                    uploadDir = uploadDir + subpath;
                    //console.log("Firefox Mode: ", uploadDir, "Target Dir", targetDir)
                }

                let hugeFileMode = "";
                if (file.size > largeFileCutoffSize){
                    //Filesize over cutoff line. Use huge file mode
                    hugeFileMode = "&hugefile=true";
                }

                let socket = new WebSocket(protocol + window.location.hostname + ":" + port + "/system/file_system/lowmemUpload?filename=" + encodeURIComponent(filename) + "&path=" + encodeURIComponent(uploadDir) + hugeFileMode);
                let currentSendingIndex = 0;
                let chunks = Math.ceil(file.size/uploadFileChunkSize,uploadFileChunkSize);
                
                //Define a function for sending a particular chunk
                function sendChunk(id){
                    var offsetStart = id*uploadFileChunkSize;
                    var offsetEnd = id*uploadFileChunkSize + uploadFileChunkSize;
                    var thisblob = file.slice(offsetStart,offsetEnd);
                    socket.send(thisblob);
                    //console.log(id + "/" + chunks);

                    //Update progress to first percentage
                    var progress = id / (chunks-1) * 100.0;
                    if (progress > 100){
                        progress = 100;
                    }
                    updateProgressForWebSocketUpload(taskUUID, progress)
                    
                }

                //Update all UI elements
                updateUploadFileCount();
                uploadingFileCount++;
                $(".uploadTask").each(function(){
                    if ($(this).attr("taskID") == taskUUID){
                        //This is the target upload task object. Hide its close button
                        $(this).find(".uploadTaskRemoveIcon").hide();
                    }
                });

                //Start sending
                socket.onopen = function(e) {
                    if (filesize < uploadFileChunkSize){
                        //This file is smaller than chunk size, set it to somwhere within 10% - 20% so it doesn't look like it is stuck
                        updateProgressForWebSocketUpload(taskUUID, 10 +  Math.floor(Math.random() * Math.floor(10)))
                    }
                    
                    //Send the first chunk
                    sendChunk(0);
                    currentSendingIndex++;
                };

                socket.onmessage = function(event) {
                    //Append to the send index
                    var incomingValue = event.data;

                    if (incomingValue == "next"){
                        if (currentSendingIndex == chunks + 1){
                            //Already finished
                            socket.send("done");
                        }else{
                            //Send next chunk
                            sendChunk(currentSendingIndex);
                            currentSendingIndex++;
                        }
                      
                    }else if (incomingValue == "OK"){
                        //Merge completed
                        $(".uploadTask").each(function(){
                            if ($(this).attr("taskID") == taskUUID){
                                //Update this progress bar to completed
                                $(this).find(".bar").css("width","100%");
                                $(this).find(".progress:not(.percentage)").attr("class", "ui tiny success progress");
                                $(this).find(".progress.percentage").hide();
                                $(this).find(".uploadTaskRemoveIcon").show();
                                $(this).addClass("ended");
                               
                                
                                $.when($(this).delay(1000).fadeOut("fast")).then(function(){
                                    $(this).remove();
                                    updateUploadFileCount();
                                });
                                
                            }
                        });
                    }else{
                        //Try to parse it as JSON
                        try{
                            var resp = JSON.parse(incomingValue.split('\\' + '"').join("\""));
                            //console.log(resp);
                            if (resp.error !== undefined){
                                //This is an error message
                                msgbox("red remove",resp.error);

                                //Update the progress bar to error
                                $(".uploadTask").each(function(){
                                    if ($(this).attr("taskID") == taskUUID){
                                        //Update this progress bar to completed
                                        $(this).find(".bar").css("width","100%");
                                        $(this).find(".progress:not(.percentage)").attr("class","ui tiny error progress");
                                        $(this).find(".uploadTaskRemoveIcon").show();
                                        $(this).addClass("ended");
                                        $(this).find(".progress.percentage").hide();
                                    }
                                });
                            }else if (resp.move !== undefined){
                                //File move from tmp to archive progress
                                //Update the progress bar to show move progress
                                $(".uploadTask").each(function(){
                                    if ($(this).attr("taskID") == taskUUID){
                                        $(this).find(".bar").css("width","100%");
                                        $(this).find(".progress:not(.percentage)").attr("class","ui small indicating themed saving progress");
                                        $(this).find(".progress.percentage").html(`<i class="ui save icon"></i> ${resp.move}`);
                                    }
                                });
                            }
                        }catch(ex){
                            //Something else
                            console.log(incomingValue);
                            console.log(ex);
                        }
                    }

                };

                socket.onclose = function(event) {
                    uploadingFileCount--;
                    updateUploadFileCount();
                     //After the previous file has uploaded / errored, check if there are another file needed to be uploaded
                    setTimeout(function(){
                        if (uploadPendingList.length > 0){
                            let nextFile = uploadPendingList.shift();
                            uploadFile(nextFile.File, nextFile.UUID, nextFile.TargetDir);
                        }
                    }, 100)
                };

                socket.onerror = function(error) {
                    console.log(error.message);
                    console.log("Unable to open WebSocket connection. Fall back to FORM POST upload mode. (Check your nginx / reverse proxy settings!!!)")
                    //Try to fallback to FORM POST upload mode
                    lowMemoryMode = false;
                   
                    uploadPendingList.push({
                        File: file,
                        UUID: taskUUID,
                        TargetDir: JSON.parse(JSON.stringify(targetDir)),
                    });
                    
                   
                    return
                };

            }else{
                /*
                    Standard Upload Mode
                */

                //Create the task progress Object
                let taskUUID = uuid;    //For queueing objects
                if (taskUUID == undefined){
                    //If this is a new file to be uploaded
                    taskUUID = appendUploadFileItem(file.name, file.size);
                    setTimeout(function(){
                        updateUploadFileCount();
                    }, 100);
                }

                //TODO: Make the upload management interface a bit better
                //return;
                
                //Updates 22-10-2020
                //Added file upload queuing system to prevent too many request on-the-fly at the same time
                if (uploadingFileCount >= maxConcurrentUpload){
                    //Push to upload pending list
                    //Sometime files will be recursively uploaded (aka retry multiple time), hence the targetDir needed to be copied as well
                    let uploadDir = currentPath;
                    if (targetDir !== undefined){
                        uploadDir = targetDir;
                    }
                    uploadPendingList.push({
                        File: file,
                        UUID: taskUUID,
                        TargetDir: JSON.parse(JSON.stringify(uploadDir)),
                    });
                    return
                }

                //Prase upload Form
                let uploadCurrentPath = JSON.parse(JSON.stringify(currentPath));
                if (targetDir !== undefined){
                    //The upload paramter supplied targetDir
                    uploadCurrentPath = targetDir;
                }
                let url = '../../system/file_system/upload?path=' + encodeURIComponent(uploadCurrentPath)
                //console.log("Uploading To => ", uploadCurrentPath, targetDir, currentPath);
                let formData = new FormData()
                let xhr = new XMLHttpRequest()
                formData.append('file', file);
                formData.append('path', uploadCurrentPath);

                //Hide the cancel upload task button
                $(".uploadTask").each(function(){
                    if ($(this).attr("taskID") == taskUUID){
                        //This is the target upload task object. Hide its close button
                        $(this).find(".uploadTaskRemoveIcon").hide();
                    }
                });

                xhr.open('POST', url, true)
                xhr.upload.addEventListener("progress", function(e) {
                    var progress = (e.loaded * 100.0 / e.total) || 100;
                    $(".uploadTask").each(function(){
                        if ($(this).attr("taskID") == taskUUID){
                            //Update this progress bar
                            $(this).find(".bar").css("width",progress + "%");
                            $(this).find(".progress.percentage").text(progress.toFixed(1) + "%");
                            if (progress == 100){
                                //When progress = 100 and the server is not response with 200,
                                //That means the upload has finish and server is processing the upload
                                $(this).find(".progress").addClass("active");
                                $(this).find(".progress.percentage").hide();

                            }
                        }
                    });
                })

                xhr.addEventListener('readystatechange', function(e) {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        //Upload process ended
                        //Update task status
                        $(".uploadTask").each(function(){
                            if ($(this).attr("taskID") == taskUUID){
                                //Update this progress bar to completed
                                $(this).find(".bar").css("width","100%");
                                $(this).find(".progress").attr("class", "ui tiny success progress");
                                $(this).find(".uploadTaskRemoveIcon").show();
                                $(this).addClass("ended");
                                //Update 15-11-2020
                                //Remove this taskbar after 1 second to prevent lags during > 2000 uploads
                                $.when($(this).delay(1000).fadeOut("fast")).then(function(){
                                    $(this).remove();
                                    updateUploadFileCount();
                                });
                                
                            }
                        });

                        var resp = JSON.parse(e.target.response);
                        if (resp.error !== undefined){
                            msgbox("caution",resp.error);
                            //Something went wrong. Set the color to red
                            $(".uploadTask").each(function(){
                                if ($(this).attr("taskID") == taskUUID){
                                    //Update this progress bar to completed
                                    $(this).find(".bar").css("width","100%");
                                    $(this).find(".progress").attr("class", "ui tiny error progress");
                                    $(this).find(".uploadTaskRemoveIcon").show();
                                    $(this).addClass("ended");
                                }
                            });
                        }
                        uploadingFileCount--;

                        //After the previous file has uploaded / errored, check if there are another file needed to be uploaded
                        setTimeout(function(){
                            if (uploadPendingList.length > 0){
                                let nextFile = uploadPendingList.shift();
                                uploadFile(nextFile.File, nextFile.UUID, nextFile.TargetDir);
                            }
                        }, 100)
                        
                    }else if (xhr.readyState == 4 && xhr.status != 200) {
                        msgbox("red remove",applocale.getString( "message/uploadFailed", "File too big or the target disk is fulled"));
                        console.log(xhr);
                        $(".uploadTask").each(function(){
                            if ($(this).attr("taskID") == taskUUID){
                                //Upload screwed up. Show error
                                $(this).find(".progress").attr("class","ui tiny error progress");
                                $(this).find(".uploadTaskRemoveIcon").show();
                                $(this).addClass("ended");
                            }
                        });
                        uploadingFileCount--;

                        //After the previous file has uploaded / errored, check if there are another file needed to be uploaded
                        setTimeout(function(){
                            if (uploadPendingList.length > 0){
                                let nextFile = uploadPendingList.shift();
                                uploadFile(nextFile.File, nextFile.UUID, nextFile.TargetDir);
                            }
                        }, 100)
                    }

                

                    updateUploadFileCount();
                })

                xhr.send(formData);
                uploadingFileCount++;
                updateUploadFileCount();
            }
        }

        //Clear all finished upload tasks
        function clearAllUploadTask(){
            $(".uploadTask.ended").slideUp('300',function(){
                $(this).remove();
                updateUploadFileCount();
            });
            
        }

        function toggleSearch(){
            //Start search mode
            $(".searchbar").show()
            initWindowSizes(true);
            
            $("#searhbtn").addClass("disabled");

            //Force videmode to list
            viewModeBeforeSearch = viewMode;
            viewMode = "list"
            $(".videmode.button").each(function(){
                 $(this).addClass('disabled');
            });
            searchMode = true;
            
            //Adjust the css for mobile interface
            if (isMobile){
                $("#searchInput").parent().parent().css("width", window.innerWidth - 135 + "px");
            }

            //Clear current folderlist
            $("#folderList").show();
            $("#folderList").html(`<div class="ui basic segment">
                <div class="ui header themed">
                    <i class="arrow up icon"></i> <span>${applocale.getString("func/search/typeToStart", "Type to Start Search")}</span>
                    <div class="sub header" style="margin-top:12px;">${applocale.getString("func/search/tip1", "Type something in the search bar to start searching.")}<br>
                        ${applocale.getString("func/search/tip2", `Start wildcard matching with "/" (slash) and your wildcard string (e.g. /*.mp3)`)}</div>
                </div>
            </div>`);
            $("#fileList").hide();
        }

        function hideSearchBar(skipFilelistRefresh = false){
            $(".searchbar").hide();
            initWindowSizes(true);
            $("#searchInput").val("");
            $("#searhbtn").removeClass("disabled");
            viewMode = viewModeBeforeSearch;
            $(".videmode.button").each(function(){
                if ($(this).attr("mode") != viewMode){
                    $(this).removeClass('disabled');
                }
            });
            if (skipFilelistRefresh == false){
                listDirectory(currentPath);
            }
            searchMode = false;
        }
        
        //Handle case sensitive in keyword searching
        function toggleCaseSensitive(btn){
            if ($(btn).hasClass("active")){
                $(btn).removeClass("active");
                searchCaseSensitive = false;
            }else{
                $(btn).addClass("active");
                searchCaseSensitive = true;
            }
        }

        function exitHotSearch(){
            hotSearchBuffer = "";
            hotSearchTimer = null;
            //Move the file to "selected" mode
            $(".hotSearchHighlight").addClass("selected");
            $(".hotSearchHighlight").removeClass("hotSearchHighlight");
        }

        function handleHotSearch(starting, offset){
            if (offset < 0){
                offset = 0;
            }

            starting = starting.toLowerCase();
            console.log(starting);
            $(".hotSearchHighlight").removeClass("hotSearchHighlight");
            let files =  $(".fileObject");
            let matchingFiles = [];
            for (var i = 0; i < files.length; i++){
                let thisFile = files[i];
                if ($(thisFile).attr("filename") != undefined && $(thisFile).attr("filename").length > starting.length && $(thisFile).attr("filename").substr(0, starting.length).toLowerCase() == starting){
                    matchingFiles.push(thisFile);
                }
            }

            //Loopback if offset overflow
            let newOffset = offset;
            if (offset > matchingFiles.length - 1){
                newOffset =offset % matchingFiles.length;
            }

            var targetHighlightingFile = matchingFiles[newOffset];
            $(targetHighlightingFile).addClass("hotSearchHighlight");
            scrollToFileLocation($(targetHighlightingFile));
            return;
            
        }

        function handleSearch(){
            var keyword = $("#searchInput").val();
            $("#folderList").html(`<div class="ui basic segment">
                <i class="loading spinner icon"></i> <span>Searching</span>
            </div>`);
            $("#fileList").hide();
            $("#fileList").html("");
           
            $.ajax({
                url: "../../system/file_system/search",
                data: {path: currentPath, keyword: keyword, casesensitive: searchCaseSensitive},
                success: function(data){
                    if (data.error !== undefined){
                        msgbox("red remove", applocale.getString("message/" + data.error, data.error));
                        hideSearchBar();
                    }else{
                        //Render the filelist
                        console.log(data);
                        if (data.length == 0){
                            $("#folderList").show();
                            $("#folderList").html(`<div class="ui basic segment">
                                <div class="ui header">
                                    <i class="question icon"></i> <span>${applocale.getString("message/noMatchResults","No Matching Results")}</span>
                                    <div class="sub header">${applocale.getString("message/noMatchResultsDesc","The host return no matching results for your keyword")} "${keyword}". <br>${applocale.getString("message/noMatchResultsInst","Check your spelling and your wildcard characters.")}</div>
                                </div>
                            </div>`);
                        }else{
                            renderDirectory(data);
                        }
                        
                    }
                }, error: function(){
                    $("#folderList").html(`<div class="ui basic segment">
                    <div class="ui header">
                        <i class="remove icon"></i> Search Error
                        <div class="sub header">Search timeout</div>
                    </div>
                </div>`);
                }
            })
        }

        function handleSearchBarPress(e){
            if (e.keyCode == 13 || e.key == "Enter"){
                e.preventDefault();
                handleSearch();
            }
        }

        function toggleCtrl(){
            ctrlHold = !ctrlHold;
            updateCtrlDisplay();
        }

        function selectAll(){
            $(".fileObject").addClass("selected");
            updateSelectedObjectsCount();
        }

        function clearSelection(){
            $('.fileObject.selected').removeClass("selected");
            updateSelectedObjectsCount();

            if (ctrlHold){
                //Deselect everything, also exit multi-select mode
                ctrlHold = false;
                updateCtrlDisplay();
            }
        }

        function updateCtrlDisplay(){
            if (isMobile){
                //Change color of the navibar based on selection mode
                if (ctrlHold){
                    $("#navibar").addClass("ctrl");
                }else{
                    $("#navibar").removeClass("ctrl");
                }
            }
        }

        function getUploadTaskByID(taskUUID){
            var task = undefined;
            $("#uploadTab").find(".uploadTask").each(function(){
                if ($(this).attr("taskid") == taskUUID){
                    task = $(this);
                }
            });

            return task;
        }

        function appendUploadFileItem(filename, filesize){
            var newuuid = uuidv4();
            var humanReadableFilesize = 0;
            if (filesize < 0){
                humanReadableFilesize = applocale.getString("message/unknownSize", "Unknown Size")
            }else{
                humanReadableFilesize = bytesToSize(filesize);
            }
            
            $("#uploadProgressList").append(`<div class="uploadTask" taskID="${newuuid}">
                <p style="width: calc(100% - 15px);">${filename} (${humanReadableFilesize})</p>
                <div class="ui small themed progress" style="margin-top:-12px;">
                    <div class="bar" style="width: 0%; min-width: 0px;">
                        <div class="progress percentage"></div>
                    </div>
                </div>
                <div class="uploadTaskRemoveIcon" onclick="removeThisTask(this, '${newuuid}');" style="">
                    <i class="remove icon"></i>
                </div>
            </div>`);
            return newuuid;
        }

        function removeThisTask(object, taskUUID){
            //Remove item from uploadPendingList
            let removeId = -1;
            for (var i = 0; i < uploadPendingList.length; i++){
                if (uploadPendingList[i].UUID == taskUUID){
                    removeId = i;
                    break;
                }
            }

            if (removeId >= 0){
                uploadPendingList.splice(removeId, 1);
            }

            //Remove the DOM Element
            $(object).parent().fadeOut('fast',
                function(){
                    $(this).remove();
                    updateUploadFileCount();
                }
            );
            
        }

        function toggleUploadList(){
            $("#uploadProgressList").toggle();
            if ($("#uploadProgressList").is(":visible")){
                $("#hideUploadButton").html('<i class="caret down icon"></i>');
            }else{
                $("#hideUploadButton").html('<i class="caret up icon"></i>');
            }
        }

        function updateUploadFileCount(){
            $("#uploadCount").text(uploadingFileCount);
            $("#waitingCount").text(uploadPendingList.length);
            if (uploadingFileCount == 0 && $(".uploadTask").length == 0){
                $("#uploadTab").hide();
            }else{
                $("#uploadTab").show();
            }
        }

        function bytesToSize(bytes) {
            var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
            if (bytes == 0) return '0 Byte';
            var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
            return Math.round(bytes / Math.pow(1024, i) * 100, 2) / 100 + ' ' + sizes[i];
        }

        function uuidv4() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        function dropToFolder(event){
            event.preventDefault();
            event.stopImmediatePropagation();
            console.log("Drop to folder detected");

            //Extract target folder path from object
            var targetPath = $(event.target).attr("filepath");
            if (targetPath == ""){
                return
            }
            
            //Check if this is upload or file move drag
            var files = event.dataTransfer.files;
            if (files.length > 0){
                //Upload mode. Extract the target folder basename from path
                if (targetPath.substr(targetPath.length -1,1) == "/"){
                    targetPath = targetPath.substr(0, targetPath.length-1);
                }
                var folderBase = targetPath.split("/").pop() + "/";
                var items = event.dataTransfer.items;
                for (let i=0; i<items.length; i++) {
                    let item = items[i].webkitGetAsEntry();
                    if (item) {
                        recursiveScanFilesUpload(item, folderBase, folderBase);
                    }
                }
            }else if (event.dataTransfer.getData("filedata") != ""){
                var targetVroot = targetPath.split(":/").shift();
                //Get the source files
                var filelist = JSON.parse(event.dataTransfer.getData("filedata"));
                if (filelist.length > 0){
                    var srcVroot = filelist[0].filepath.split(":/").shift();
                    if (srcVroot == targetVroot){
                        //Use move mode
                        cutMode = true;
                        
                    }else{
                        //Use copy mode
                        cutMode = false;
                    }

                    //Parse the filelist
                    clipboard = [];
                    filelist.forEach(file=>{
                        clipboard.push(file.filepath);
                    });
                    if (useLocalstorage){
                        localStorage.setItem("ao/file_system/clipboard",JSON.stringify(clipboard));
                        localStorage.setItem("ao/file_system/cutmode","true");
                    }
                    
                    //Perform operations
                    paste(targetPath, false)
                }
            }
        }

        function allowDrop(event){
            event.preventDefault();
        }

        $(".popupWrapper").on("click",function(){
            hideAllPopupWindows();
        });

        function hideAllPopupWindows(){
            $(".popup:visible").transition('slide left out');
            $(".popupWrapper").fadeOut(100);
            $('body').css("overflow","");
            if($("#shareFile").is(":visible")){
                $("#shareFileEmbedded").attr("src", "");
            }
        }

        function showPopupWrapper(){
            $(".popupWrapper").fadeIn('fast');
            $('body').css("overflow","hidden");
        }

        //Handle keydown of enter on certain input boxes
        function handleEnterKeyDown(event, handler){
            if (event.which == 13){
                handler();
            }
        }

        //Generate a download link and press it
        function generateDownloadFromURL(url, filename){
            let a = document.createElement('a')
            a.href = url;
            a.download = filename;
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
        }

        //Update sorting method for file listing
        function updateSortingMethods(){
            var method = $("#sortingMethodSelector").val();
            sortMode = method;

            //Save it to server side
            $.ajax({
                url: "../../system/file_system/sortMode",
                method: "POST",
                data: {opr: "set", folder: currentPath, mode: sortMode},
                success: function(data){
                    //console.log("Sort mode saved: " + data)
                    refreshList();
                }
            });
        }

        /*
            Properties Sidebar
        */

        function loadFileProperties(filepath){
            $.ajax({
                url: "../../system/file_system/getProperties",
                method: "POST",
                data: {path: filepath},
                success: function(data){
                    if (data.error !== undefined){
                        //Failed to load 

                    }else{
                        let previewSidebar = $("#propertiesView");
                        //Check the extension. If the extension is image supported 
                        //by web browser, enable full resolution button
                        let enableFullResButton = false;
                        if (!data.IsDirectory && data.Basename.indexOf(".") >= 0){
                            let ext = data.Basename.split(".").pop().toLowerCase();
                            if (ext == "jpeg" || ext == "jpg" || ext == "webp" || ext == "png" || ext == "gif"){
                               //Web preview-able formats

                            }
                        }
                        
                        //Load the preview 
                        fetch("../../system/file_system/loadThumbnail?vpath=" + encodeURIComponent(data.VirtualPath))
                        .then((response) => response.json())
                        .then((imageData) => {
                            if (imageData.error !== undefined || imageData.trim() == ""){
                                //Image load error.
                                if (data.IsDirectory){
                                    //Load the folder image
                                    $(previewSidebar).find(".preview img").attr("src", "../../img/system/folder.svg")
                                }else{
                                    let icon = "file outline";
                                    let ext = data.Basename.split(".").pop().toLowerCase();
                                    if (ext != ""){
                                        icon = ao_module_utils.getIconFromExt(ext);
                                    }
                                    let imagePath = "../../img/desktop/files_icon/default/" + icon + ".png";
                                    $(previewSidebar).find(".preview img").attr("src", imagePath);
                                }
                               
                                return;
                            }
                            $(previewSidebar).find(".preview img").attr('src',"data:image/jpg;base64," + imageData);
                        });

                        //Render the remaining information
                        $("#propertiesView").find(".filename").text(data.Basename);
                        $("#propertiesView").find(".vpath").text(data.VirtualPath);

                        let propTable = $("#propertiesView").find(".propertiesTable");
                        let styleOverwrite = `min-width: 4em;`;
                        $(propTable).html("");
                        $(propTable).append(`<tr>
                            <td style="${styleOverwrite}">
                                ${applocale.getString("sidebar/properties/filesize", "File Size")}
                            </td>
                            <td>
                                ${bytesToSize(data.Filesize)}
                            </td>
                        </tr><tr>
                            <td style="${styleOverwrite}">
                                ${applocale.getString("sidebar/properties/modtime", "Last Modification")}
                            </td>
                            <td>
                                ${data.LastModTime}
                            </td>
                        </tr><tr>
                            <td style="${styleOverwrite}">
                                ${applocale.getString("sidebar/properties/mimetype", "MIME Type")}
                            </td>
                            <td>
                                ${data.MimeType}
                            </td>
                        </tr><tr>
                            <td style="${styleOverwrite}">
                                ${applocale.getString("sidebar/properties/owner", "Owner")}
                            </td>
                            <td>
                                ${data.Owner}
                            </td>
                        </tr><tr>
                            <td style="${styleOverwrite}">
                                ${applocale.getString("sidebar/properties/permission", "Permission")}
                            </td>
                            <td>
                                ${data.Permission}
                            </td>
                        </tr><tr>
                            <td style="${styleOverwrite}">
                                ${applocale.getString("sidebar/properties/storepath", "Storage Path")}
                            </td>
                            <td style="word-break: break-all;">
                                ${data.StoragePath}
                            </td>
                        </tr><tr>
                            <td style="${styleOverwrite}">
                                ${applocale.getString("sidebar/properties/vpath", "Virtualized Path")}
                            </td>
                            <td style="word-break: break-all;">
                                ${data.VirtualPath}
                            </td>
                        </tr>`);

                    }
                }
            })
        }

        //Toggle preview windows size from small to large mode,
        //set restoreDefault to true for force small interface
        function togglePreviewWindowSize(restoreDefault = false){
            if ($("#propertiesView").hasClass("small") && restoreDefault == false){
                //Set it to big
                $("#propertiesView").css({
                    "width": "500px",
                    "min-width": "500px"
                });
                $("#propertiesView").removeClass("small").addClass("big");
                $("#propertiesView").find(".sizeToggle").html(`<i class="compress icon"></i>`);
                $("#propertiesView").find(".sizeToggle").attr("title", applocale.getString("sidebar/properties/shrink", "Shrink Properties Sidebar"));
            }else{
                //Set it to small
                $("#propertiesView").css({
                    "width": "300px",
                    "min-width": "300px"
                });
                $("#propertiesView").removeClass("big").addClass("small");
                $("#propertiesView").find(".sizeToggle").html(`<i class="expand icon"></i>`);
                $("#propertiesView").find(".sizeToggle").attr("title", applocale.getString("sidebar/properties/expand", "Expand Properties Sidebar"));
            }
        }

        /*
            Integration functions
        */

        //Request CSRF token before any file operation API Calls for better security
        function requestCSRFToken(callback){
            $.ajax({
                url: "../../system/csrf/new",
                success: function(token){
                    callback(token);
                }
            })
        }

        //Overwrite of the ao_module_close
        function ao_module_close(){
            if (uploadPendingList.length > 0 || uploadingFileCount > 0){
                //There are pending upload item or uploading items
                //ask the user to confirm exit
                hideAllPopupWindows();
                showPopupWrapper();
                $("#confirmExit").transition("slide left in");
                return
            }
            //Exit window
            ao_module_closeHandler();
        }

        </script>
    </body>
</html>